PHP XML解析 [英] PHP XML Parsing

查看:61
本文介绍了PHP XML解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方法是解析PHP中XML文件的最佳方法?

Which is the best way to parse an XML file in PHP ?

第一
使用DOM对象

First
Using the DOM object

//code
$dom = new DOMDocument();
$dom->load("xml.xml");

$root = $dom->getElementsByTagName("tag");
foreach($root as $tag)
{
$subChild = $root->getElementsByTagName("child");

// extract values and loop again if needed
}

第二
使用simplexml_load方法

Second
Using the simplexml_load Method

// code
$xml = simplexml_load_string("xml.xml");
$root = $xml->root;
foreach($root as $tag)
{
$subChild = $tag->child;
// extract values and loop again if needed
}

注意: 这是我所知道的两个.如果还有更多的内容.

Note : These are the two I am aware of. If there are more fill in.

想知道哪种方法最适合解析大型XML文件,哪一种方法最快,无论该方法的实现方式如何

Wanted to know which method is the best for parsing huge XML files, also which method is the fastest irrespective of the way the method needs to be implemented

大小从500KB到2MB不等.解析器应该能够在最短的时间内解析大小文件,并尽可能地利用良好的内存.

Size will be varying from 500KB to 2MB. The parser should be able to parse small as well as large files in the least amount of time with good memory usage if possible.

推荐答案

我已经开始使用XMLReader解析XML文件.经过一番探索之后,发现最好的方法是解析XML文件,因为它不会将整个XML文件加载到内存中.假设我的XML文件大小为5 MB,那么使用XMLReader解析它时,不会浪费我5MB的内存.

I have started to use XMLReader to parse the XML files. After doing a bit of googling around found it the best to way parse XML files as it does not load the whole XML file into memory. Say if suppose my XML files was of 5 MB, while parsing it using XMLReader 5MB of my memory does not get wasted.

//usage
$xml = new XMLReader();
$xml->XML($xmlString);
while($xml->read)
{
if($xml->localName == 'Something') // check if tag name equals something
{
//do something
}
}

使用XML Reader,我们可以找到当前标签是开始标签还是结束标签,并根据需要进行处理.

Using XML Reader we can find if the current tag is an opening tag or closing tag and do the needful as required.

这篇关于PHP XML解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆