Search code examples
phpxmlsimplexmlopendir

read many xml file in a folder whith simplexml


Should I read many xml file in a folder and extract from these data. I have no problem to read the folder with this code

<?php
$dir = "Dati/xml/nonletti/";
  if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
      if (($file !== '.') && ($file !== '..') ) {
  echo "$file \n";
  }
}
  closedir($dh);
}
}
?>

but if I try to use simplexml to read all the files do not I see anything

<?php
$dir = "Dati/xml/nonletti/";
if (is_dir($dir)) {
  if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
      if (($file !== '.') && ($file !== '..') ) {
    $xml = simplexml_load_file($file);  
        $RGSostituzione = $xml->attributes()->Sostituzione;
    echo "<li>File $file - <b>Sostituzione:</b> $RGSostituzione</li>";
    }
  }
  closedir($dh);
  }
}
?>

Can you help me and tell me how to do? thank's- Filippo


Solution

  • When you read the files in the directory, you only get the base filename, not the full path. So you need to prepend the path when you do the SimpleXML call.

    Change to:

    $xml = simplexml_load_file($dir . $file);