1

I have to parse automatic generate XML files to PHP, without success.

I'm fetching a folder with XML files and each file has to be parsed. The weird thing is, that I only get the version as output.

My code:

$xml_folder = "/var/www/sitename/xml_folder/";
$xml_files  = scandir($xml_folder);
$xml_files  = array_diff($xml_files, array('.', '..'));

foreach($xml_files as $file) {
    $xml_file = $xml_folder . $file;
    $xml = simplexml_load_file($xmlfile);
    print_r($xml);
}

Now, my output looks like this:

The XML looks like a normal generated XML, here is a screenshot preview of it:

Sure, it's not structured, but any browser can handle it and creates a valid structure.

Is the structure important for simplexml? I tried a bunch of variations to make it work (even with simplexml_load_string), but nothing won't work.

Matt Backslash
  • 764
  • 1
  • 8
  • 20
  • I'm guessing it works fine. Try this: `echo htmlentities( print_r( $xml, 1 ) );`. Your browser just doesn't display the XML tags. Try a view-source on your page, and you'll see it's all there (I hope). – Kenney Feb 09 '16 at 16:02
  • Just a guess, but your problem may not be XML but use of the `print_r` function. I don't see any reason to expect print_r to output the actual XML. – Elliotte Rusty Harold Feb 09 '16 at 16:04
  • Hmm, doesn't look like it's because of `print_r()`. With `echo htmlentities(print_r($xml,1));` it just outputs the same as in the screenshot. – Matt Backslash Feb 09 '16 at 16:16

1 Answers1

1

You should never use print_r for XML, it does not work nicely for xml.
Instead you can use this to show the xml structure

echo $xml->asXML();

Check the answer from: SimpleXML and print_r() - why is this empty?

Don't use print_r() or var_dump() to inspect a SimpleXMLElement, they won't necessarily work on them because SimpleXML uses lots of magic behind the scene. Instead, look at what asXML() returns.

Community
  • 1
  • 1
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
  • Works very good, but how can i loop into the output from `$xml->asXML()`? If I `print_r()` something like `$xml->asx` (like in my screenshot), I just get the error `Trying to get property of non-object`. My goal is to make the whole XML into an PHP array. – Matt Backslash Feb 09 '16 at 16:44
  • Check this: http://stackoverflow.com/questions/6167279/converting-a-simplexml-object-to-an-array – Niki van Stein Feb 09 '16 at 16:47