-2

我有以下格式的 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 个。

4

3 回答 3

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;
?>
于 2012-08-10T11:51:57.063 回答
0

如果您只需要一种没有相对限制的节点类型的统计信息,则 DOM::getElementsByTagName 就足够了,因为它返回具有“长度”只读属性的 DOMCollection。

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

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

于 2012-08-10T11:20:39.563 回答
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
于 2012-08-10T11:15:16.423 回答