简体   繁体   English

PHP-计数XML子节点

[英]PHP - Count XML Child Nodes

I have XML that looks like the following: 我有看起来像下面的XML:

<?xml version="1.0" encoding="UTF-8"?>
<apiresponse>
  <response>
    <services>
      <service>
        <Carrier>Carrier1</Carrier>
      </service>
      <service>
        <Carrier>Carrier2</Carrier>
      </service>
      <service>
        <Carrier>Carrier3</Carrier>
      </service>
      <service>
        <Carrier>Carrier4</Carrier>
      </service>
    </services>
  </response>
</apiresponse>

This is stored inside the variable $result . 这存储在变量$ result中

I want to count the number of nodes within services . 我想计算服务中的节点数。 How do I go about this when the services node doesn't have a name or ID? 当服务节点没有名称或ID时该如何处理?

I tried the following but it didn't work: 我尝试了以下操作,但没有成功:

$xml = new SimpleXMLElement($result);
echo count($xml->services);

Thanks! 谢谢!

you can simply use this: 您可以简单地使用:

echo $xml->response->services->service->count();

or you use a loop: 或者您使用循环:

$xml = new SimpleXMLElement($result);

foreach ($xml as $services) {
    foreach($services as $service) {
        echo "<pre>";
        print_r($service->count());
        echo "</pre>";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM