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 Commented 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>";
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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!
another foreach to loop the services: foreach ($xml as $services) { foreach($services as $service) { foreach($service as $carrier) { echo $carrier->Carrier . '<br/>'; } } }

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.