PHP -> Generate XML

Hello everybody, I’m terrible with xml. I am trying to read a folder on my computer and generate an xml file from there. The code that I have made ​​this place without problems, but I need to generate an xml code like this:

<? xml version = '1 .0 'encoding =' UTF-8 '?>
<gallery>
     <image imgurl="assets/sxc_hu_410471_5588.jpg"> </ image>
     <image imgurl="assets/sxc_hu_1151936_79441078.jpg"> </ image>
     <image imgurl="assets/sxc_hu_1152040_85122875.jpg"> </ image>
     <image imgurl="assets/sxc_hu_1154131_54136948.jpg"> </ image>
</ gallery>

But my nice code :rofl: looks like this:

<? xml version = "1.0" encoding = "UTF-8"?>
<gallery>
<image imgurl="images/bacdk.jpg"/> <image imgurl="images/back.jpg"/> <image imgurl="images/back.png"/> <imgURL image = "images/back2.jpg" /> <image imgurl="images/badck.jpg"/> <image imgurl="images/blue_hills.jpg"/> <image imgurl="images/body-altura.jpg"/> <imgURL image = "images / sunset.jpg "/> <image imgurl="images/Thumbs.db"/> <image imgurl="images/winter.jpg"/> </ gallery>

Can someone help me make it in this code here:

<php
$ path_to_image_dir = 'images';
xml_string $ = <<<XML
<? xml version = "1.0" encoding = "UTF-8"?>

<gallery>
</ gallery>
XML;

xml_generator $ = new SimpleXMLElement ($ xml_string);

if ($ handle = opendir ($ path_to_image_dir))
{
     while (false! == ($ file = readdir ($ handle)))
     {
         if (is_file ($ path_to_image_dir .'/'.$ file))
         {
            list ($ width, $ height) = getimagesize ($ path_to_image_dir .'/'.$ file);
            $ image = $ xml_generator;
            $ preview = $ image-> addChild ("image");

            $ preview ['imgURL'] = $ path_to_image_dir .'/'.$ file;
    }
     }
     closedir ($ handle);
}

$ file = fopen ('content.xml', 'w');
fwrite ($ file, $ xml_generator-> asXML ());
fclose ($ file);
?>

I can not connect the dots please someone help me! Thanks in advance!

I think they should be equivalent, but maybe you’re after something to help formatting? If not, just shout. :slight_smile:


 <?php
function format_simple_xml(SimpleXMLElement & $xml){
  $doc = new DOMDocument;
  $doc->preserveWhiteSpace = false;
  $doc->formatOutput = true;
  $doc->loadXML($xml->asXML());
  return $doc->saveXML();
}

I’m also looking for something to help me formatting but I would like to organize the first output of the code like this:
My code is returning

<gallery>
<image imgurl="images/bacdk.jpg"/> [...]

This character here is also wrong here “images/bacdk.jpg”/>
when I want to return:
<gallery>
<image imgurl=“assets/sxc_hu_410471_5588.jpg”> </ image>
</gallery>
How can I do?

Check the libxml options (which you can pass into the SimpleXML object constructor), notably the LIBXML_NOEMPTYTAG option. :slight_smile: