Question

I get this

XML Parsing Error: junk after document element Location: xxxxxxxxx Line Number 2, Column 1

This is the code :

<?php

$xml_generator = new SimpleXMLElement('<data/>');

filesindir('assets/images/');
function filesindir($dirs) {
    $dirs = scandir($tdir);
    while ($file = readdir($dirs)) {
            if (($file == '.')||($file == '..')) {
            } elseif (is_dir($tdir.'/'.$file)) {
                filesInDir($tdir.'/'.$file);
            } else {
                $image = $xml_generator->addChild('image');  
                $image->addChild('name', $file);
            }
    }
}

header("Content-Type: text/xml");
$xml_generator->asXML('data.xml');
echo $xml_generator->asXML();
?>

What did I do wrong?

Was it helpful?

Solution

So many thing wrong .. look like you copied and merged so many codes ..

Try

$xml = new SimpleXMLElement('<data/>');

scanFiles(__DIR__, $xml);

function scanFiles($path, SimpleXMLElement $xml, $allowed = array("jpg","png")) {
    $list = scandir($path);
    foreach ( $list as $file ) {
        if ($file == "." || $file == ".." || ! in_array(pathinfo($file, PATHINFO_EXTENSION), $allowed))
            continue;
        $image = $xml->addChild('image');
        $image->addChild('name', $file);
        $image->addChild('size', filesize($file));
    }
}

header("Content-Type: text/xml");
$xml->asXML('data.xml');
echo $xml->asXML();

Output

<?xml version="1.0"?>
<data>
  <image>
    <name>a.jpg</name>
    <size>17129</size>
  </image>
  <image>
    <name>a2.jpg</name>
    <size>11100</size>
  </image>
  <image>
    <name>fake.png</name>
    <size>167</size>
  </image>
</data>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top