PHP XMLReader从某个节点元素编号开始读取

问题描述 投票:0回答:1

不确定这是否可行,例如,如果我有一个包含数百万个“item”元素的XML文件,我可以跳过1 - 100“item”元素并从“item”元素编号101开始读取吗?

XML示例:

<items>
   <item>
      <name>ABC</name>
      <price currency='USD'>100</price>
   </item>
   <item>
      <name>DEF</name>
      <price currency='USD'>120</price>
   </item>
   <!-- .... and a lot more item elements -->
</items>

这是我目前的代码:

$z = new XMLReader;
$z->open('1.xml');
$doc = new DOMDocument;
while ($z->read() && $z->name !== 'item');
$i = 1;
while ($z->name === 'item'){
   if($i<=100){
      $z->next('item');
   }else{
      $node = new SimpleXMLElement($z->readOuterXML());
      //doing my stuff here, extracting the node information of that <item>
      $z->next('item');
   }
   $i++;
}

从上面可以看到,我只是使用“next”跳过项目编号1-100,但这不是很有效。如果你们可以提供帮助,我们会感激不尽。谢谢!!

试过来自@DHRUV GUPTA的解决方案:

$xml=simplexml_load_file('1.xml',"SimpleXMLElement", LIBXML_COMPACT | LIBXML_PARSEHUGE);
$xml = json_encode($xml);
$xml = json_decode($xml,true);
for($i=99; $i<=104; $i++){
   echo $xml["item"][$i]["name"]."<br />";
}

但得到“解析器错误:内存不足错误”错误。

php xml xmlreader
1个回答
0
投票

是的可能,您需要遍历项目并从第99项开始。例如:-

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
$xml = json_encode($xml); // encoding in json format
$xml = json_decode($xml,true); // again decode with second parameter true to get object as array
for($i=99; $i<count($xml['items']); $i++){
  // here you can use $xml['items'][$i] which will be 100th element
}

对于大文件,您需要在simplexml_load_string函数中使用LIBXML_PARSEHUGE标志。

simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_COMPACT | LIBXML_PARSEHUGE)

XML_PARSE_HUGE标志放松了解析器的任何硬编码限制。这会影响文档的最大深度或实体递归等限制,以及文本节点大小的限制。

在大文件的情况下增加php内存限制

ini_set('memory_limit','1024M');
© www.soinside.com 2019 - 2024. All rights reserved.