Count the frequency of occurrence of a particular element or attribute in an XML document.
Use PEAR's XML_Statistics class:
- <?php
- $xmlData =<<< END
- <?xml version='1.0'?>
- <library>
- <movie>
- <title>The Matrix</title>
- <cast>
- <person>Keanu Reeves</person>
- <person>Laurence Fishburne</person>
- <person>Carrie-Anne Moss</person>
- </cast>
- </movie>
- <movie>
- <title rating="3">Mission: Impossible III</title>
- <cast>
- <person>Tom Cruise</person>
- <person>Ving Rhames</person>
- <person>Laurence Fishburne</person>
- </cast>
- </movie>
- <movie>
- <title rating="5">Minority Report</title>
- <cast>
- <person>Tom Cruise</person>
- <person>Max von Sydow</person>
- </cast>
- </movie>
- </library>
- END;
- // include class
- include "XML/Statistics.php";
- // analyze XML string
- $obj = new XML_Statistics();
- $obj->analyzeString($xmlData);
- // count total number of elements
- // result: "Total number of elements: 18"
- echo "Total number of elements: " . $obj->countTag() . "/n";
- // count total number of <person> elements
- // result: "Total number of elements: 8"
- echo "Total number of <person> elements: " .↩
- $obj->countTag('person') . "/n";
- // count total number of attributes
- // result: "Total number of attributes: 2"
- echo "Total number of attributes: " . $obj->countAttribute() . "/n";
- // count total number of text elements
- // result: "Total number of text elements: 11"
- echo "Total number of text elements: " . $obj->countDataChunks() . "/n";
- ?>
Comments
PEAR's XML_Statistics class, available from http://pear.php.net/package/XML_Statistics, enables you to retrieve information on the number of elements, attributes, CDATA blocks, PIs, and entities within an XML file or string. Once an object of the class is initialized, the analyzeString() or analyzeFile() method statistically analyzes the XML data and builds an internal frequency table for the data within it. The countTag(), countAttribute(), and countDataChunks() methods can then be used to obtain totals for the number of elements, attributes, and character data blocks respectively; these totals may be further filtered by supplying a specific element or attribute name to the corresponding method.
Note | This example also requires the XML_Parser class from http://pear.php.net/package/XML_Parser. |