PHP - 计算XML子节点

时间:2015-01-12 14:42:36

标签: php xml

我的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>

它存储在变量 $ result

我想计算服务中的节点数量。当服务节点没有名称或ID时,我该如何解决这个问题呢?

我尝试了以下但是没有用:

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

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以简单地使用它:

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

或者您使用循环:

$xml = new SimpleXMLElement($result);

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