Search code examples
phpxmlparsingsimplexml

simplexml parse xml only version


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.


Solution

  • 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.