Count all elements of a certain name in an XML file using PHP -
given xml below:
<items> <item>...</item> <item>...</item> <item>...</item> <item>...</item> </items>
i writing function return count of <item>
elements (4 in case). actual xml file huge , don't want load entire thing in memory in order parse it.
using command line, managed need following line:
grep "<item>" my_file.xml -o | wc -l
is there equivalent solution in php can use same result?
it done xpath:
$doc = new domdocument(); $doc->load('my_file.xml', libxml_parsehuge); $xp = new domxpath($doc); $count = $xp->evaluate('count(//item)');
the xpath expression returns number of all item
tags in document.
the libxml_parsehuge
option affects internal limits on depth, entity recursion, , size of text nodes. however, dom parser loads entire document memory.
for huge files, use sax parser, operates on each piece of xml sequentially (and loads small portion of document memory):
$counter = 0; $xml_parser = xml_parser_create(); xml_set_element_handler($xml_parser, function ($parser, $name) use (&$counter) { if ($name === 'item') { $counter++; } }, null); if (!($fp = fopen('my_file.xml', 'r'))) { die('could not open xml input'); } while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { die(sprintf("xml error: %s @ line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } } xml_parser_free($xml_parser);
Comments
Post a Comment