-2

I am new to php and I am trying to create a file upload system that will automatically parse the xml file using simplexml. I have created a php script that will open the directory and try to parse the files. For some reason, it will only parse one of the files. I am not sure if this is the best way to aproach this task.

 <?php
$dir = "path/to/xmlfiles"
chdir($dir);

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
      $xml = simplexml_load_file($file);
      $nombre = $xml ->xpath("//NOMBRE");
      $rpu = $xml ->xpath("//RPU");
      echo (string) $nombre[0];
      echo (string) $rpu[0];
      echo $file;
    }
    closedir($dh);
  }
}
?>

For this script, I am able to echo the results just fine, the only problem is that it will only echo one of the xml file resutls.

Hopefully someone with more experience could give me a tip on how to achieve this.

For extra points, I am also trying to insert an entry to a Mysql database for each parsed file.

;) Thank you in advance for all your help.

3
  • For extra points, :) Commented Dec 5, 2019 at 16:33
  • Start by looking at scandir() in the manual Commented Dec 5, 2019 at 16:36
  • and if files have all the similiar structure you can look at stackoverflow.com/questions/23932102/… Commented Dec 5, 2019 at 16:37

1 Answer 1

1

readdir() reads directory entries as they're stored on disk (i.e., it doesn't sort entries) so it's very likely that . (current directory) will be the first one. That will make simplexml_load_file() fail and $xml will become false so $xml->xpath() will crash the script with a fatal error.

PHP should be reporting all this. If you cannot see it, it's very likely that you haven't configured PHP to display errors.

You need to filter out entries (the bare minimum would be to check they are actual files and not directories) and add some error checking here and there.

An alternative approach:

foreach (glob("$dir/*.xml") as $file) {
}
Sign up to request clarification or add additional context in comments.

Comments

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.