1

I have XML that looks like the following:

<?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.

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?

I tried the following but it didn't work:

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

Thanks!

1
  • there is no <services> at the top of your xml. it'd be $xml->response->services
    – Marc B
    Jan 12, 2015 at 14:49

1 Answer 1

1

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>";
    }
}
2
  • This works great! If I wanted to loop through each service and grab the Carrier value, how would I edit your loop? I can't quite get my head round it - Thanks!
    – Lee
    Jan 12, 2015 at 15:02
  • another foreach to loop the services: foreach ($xml as $services) { foreach($services as $service) { foreach($service as $carrier) { echo $carrier->Carrier . '<br/>'; } } }
    – goldlife
    Jan 12, 2015 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.