查找xml文件中节点的出现次数

时间:2012-08-10 11:09:15

标签: php xml

我有一个格式如下的XML文件: -

<EticketCanStatusRes>
        <ETicket>
          <eticketno>asdf4511</eticketno>
          <flightuid>57490</flightuid>
          <passuid>91832</passuid>
          <PnrNumber>AADS12</PnrNumber>
          <Origin>COK</Origin>
          <Destination>DEL</Destination>
        </ETicket>
         <ETicket>
          <eticketno>asdf4511</eticketno>
          <flightuid>57490</flightuid>
          <passuid>91832</passuid>
          <PnrNumber>AADS12</PnrNumber>
          <Origin>COK</Origin>
          <Destination>DEL</Destination>
        </ETicket>
</EticketCanStatusRes>';

我需要找出有多少<ETicket>个元素。在我的例子中有2个。

3 个答案:

答案 0 :(得分:0)

您可以使用simplexmlxpath

$string = '<EticketCanStatusRes>
        <ETicket>
          <eticketno>asdf4511</eticketno>
          <flightuid>57490</flightuid>
          <passuid>91832</passuid>
          <PnrNumber>AADS12</PnrNumber>
          <Origin>COK</Origin>
          <Destination>DEL</Destination>
        </ETicket>
         <ETicket>
          <eticketno>asdf4511</eticketno>
          <flightuid>57490</flightuid>
          <passuid>91832</passuid>
          <PnrNumber>AADS12</PnrNumber>
          <Origin>COK</Origin>
          <Destination>DEL</Destination>
        </ETicket>
</EticketCanStatusRes>';

$xml = new SimpleXMLElement($string);
$result = $xml->xpath('//ETicket');
echo count($result); // 2

答案 1 :(得分:0)

如果你想要一个只有一种类型的节点而没有相对限制的统计数据,那么DOM :: getElementsByTagName就足够了,因为它返回一个具有“length”只读属性的DOMCollection。

$document = new DOMDocument;
$document->load("your file.xml");
echo $document->getElementsByTagName('tagname')->length;

如果您想提供更多限制,可以像使用@Arkh所述的SimpleXML一样使用XPath,或者使用DOMDocument。

答案 2 :(得分:0)

我把xml文件和php文件放在同一个目录中,所以代码就像这样

     <?php
$dom = new DOMDocument;
// load the XML string defined above
$dom->load('tiket.xml');


$etickets = $dom->getElementsByTagName('ETicket');
$count = 0;

foreach ($etickets as $etiket) {
    $count++;
}

echo $count;
?>