Sam Brueton
Sam Brueton

Reputation: 69

Get Count of XML nodes in PHP

I have an XML file structure that I am reading:

XML:

<?xml version="1.0" encoding="utf-8" ?>
 <datafiles>
   <datafile>aida_rtd_call1.xml</datafile> 
   <datafile>aida_rtd_callback.xml</datafile>        
 </datafiles>

I want to be able to loop through each datafile element, get the value and pass it to a method. Here is what I have so far:

PHP:

$xml=simplexml_load_file("conf/DataFiles.xml"); 

//TODO: Count how many items 
$count = 0;

for ($x = 0; $x <= $count; $x++) {
    $xmlItem=$xml->datafile[$x];
    $fileName = "xml/";
    $fileName .= $xmlItem;
    prepareFile($fileName);     
    } 

I am struggling to figure out how I get a count of datafiles to loop though. Using my XML file structure i need it to count the two datafiles and use them on the for loop. Any ideas how to do this?

I am completely new to PHP so this may not even be the best way.

Upvotes: 0

Views: 340

Answers (2)

iainn
iainn

Reputation: 17417

You can get a count of SimpleXML child-nodes just by using PHP's native count function:

echo count($xml->datafile);
// 2

In this case, rather than using a for loop and a count, it might make more sense just to use a foreach loop instead:

foreach ($xml->datafile as $xmlItem) {
  $fileName = "xml/";
  $fileName .= $xmlItem;
  ...
}

See https://eval.in/951668 for a quick example

Upvotes: 1

Kamil Musial
Kamil Musial

Reputation: 36

$xml->children()->datafile->count()

But as suggested in comments:

foreach ($xml->children()->datafile as $element) {
    var_dump($element);
}

makes more sense

Upvotes: 0

Related Questions