Search code examples
phpxmlsimplexml

Count how many children are in XML with PHP


i know a few about php, so sorry for the question:

i have this file xml:

 <?xml version="1.0" encoding="ISO-8859-1"?>
  <alert>
   <status> </status>
   <nothing> </nothing>
   <info>
    <area>
    </area>
   </info>
   <info>
    <area>
    </area>
   </info>
   <info>
    <area>
    </area>
   </info>
  </alert>

i must do a for loop and inside a "foreach" for each The problem is that i'm not sure what is a way to know how many times i had to repeat a for loop. Because in this file xml (that is an example) i don't know how many are

Is good if:

$url = "pathfile";
$xml = simplexml_load_file($url);
$numvulcani = count($xml->alert->info); // is good ?

for ($i = 0; $i <= $numvulcani; $i++) {
 foreach ($xml->alert->info[$i] as $entry) {
  $area = $entry->area;
 }
}

is true ?

sorry for bad english


Solution

  • Try replacing foreach ($xml->alert->info[$i] as $entry) with:

     foreach ($xml->alert->info[$i] as $j => $entry)
    

    The current item index will be $j