Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

php count xml elements

Hi what is the best way to count the number of elements in a XML file? In my case I want to count the number of XML tags with the name "OfferName" within the tag "OfferNameList".

The XML below is contained in a php variable $offers

$offers = '<OfferNameList>
  <OfferName>...</OfferName>
  <OfferName>...</OfferName>
  <OfferName>...</OfferName>
  ...
</OfferNameList>';

Thanks for the help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With DOM you can either use

$dom->getElementsByTagName('OfferName')->length;

to count all OfferName elements only. length is an attribute of DOMNodeList.

To count all OfferName elements within an OfferNameList, you can use DOMXPath::evaluate

$xpath->evaluate('count(//OfferNameList/OfferName');

Note that within is somewhat inaccurate here as the XPath query will only consider direct children. Please adjust your question if you need OfferName elements anywhere below a OfferNameList element.

Also note that // will query anywhere in the document, which might be less efficient for large documents. If you know OfferNameList elements occur at a certain position in your XML only, use a direct path.


Full working example (run on codepad):

$xml = <<< XML
<root>
    <NotOfferNameList>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
    </NotOfferNameList>
    <OfferNameList>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
      <OfferName>...</OfferName>
    </OfferNameList>;
</root>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

// count all OfferName elements
echo $dom->getElementsByTagName('OfferName')->length, PHP_EOL; // 6

// count all OfferNameList/OfferName elements
$xp = new DOMXPath($dom);
echo $xp->evaluate('count(//OfferNameList/OfferName)'); // 3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...