这一切都取决于工作单元有多大,但我想你正在尝试对待每个< product />节点。
为此,最简单的方法是使用XMLReader获取到每个节点,然后使用SimpleXML来访问它们。这样,你保持内存使用率低,因为你一次处理一个节点,你仍然利用SimpleXML的易用性。例如:
$z = new XMLReader;
$z->open('data.xml');
$doc = new DOMDocument;
// move to the first node
while ($z->read() && $z->name !== 'product');
// now that we're at the right depth, hop to the next until the end of the tree
while ($z->name === 'product')
{
// either one should work
//$node = new SimpleXMLElement($z->readOuterXML());
$node = simplexml_import_dom($doc->importNode($z->expand(), true));
// now you can use $node without going insane about parsing
var_dump($node->element_1);
// go to next
$z->next('product');
}
快速概述不同方法的利弊:
仅限XMLReader
>优点:快,使用少记忆
>缺点:过于难以编写和调试,需要大量的用户级代码做任何有用的事情。用户级代码很慢,容易出错。此外,它为您留下了更多的代码维护
XMLReader SimpleXML
>优点:不使用大量的内存(只需要处理一个节点所需的内存),SimpleXML是,顾名思义,真的很容易使用。
>缺点:为每个节点创建一个SimpleXMLElement对象不是很快。你真的要做基准测试,以了解这是否是一个问题。即使一个适度的机器将能够每秒处理一千个节点。
XMLReader DOM
>优点:使用与SimpleXML相同的内存,并且XMLReader::expand()比创建一个新的SimpleXMLElement更快。我希望有可能使用simplexml_import_dom(),但它似乎并不工作在这种情况下
>缺点:DOM很讨厌使用。它在XMLReader和SimpleXML之间。不像XMLReader那么复杂和尴尬,但光年使用SimpleXML。
我的建议:用SimpleXML编写一个原型,看看它是否适合你。如果性能是最重要的,请尝试DOM。尽可能远离XMLReader。记住,你编写的代码越多,引入错误或引入性能回退的可能性就越高。