Search code examples
javascriptphpxmldom

Create an XML file using Javascript or PHP


I have a XML file as follows:

<bracelets>
     <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" />
     <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" />
     <photo filename="b3.jpg" thumbnail="a3.jpg" description="aa" />
     <photo filename="b4.jpg" thumbnail="a4.jpg" description="aa" />
</bracelets>

I want to fetch all image names into a .php page.

I am using this now.

$bracelets = simplexml_load_file($bracelets_xml);
        x = xmlDoc.getElementsByTagName('photo')[0].attributes;
        for (i = 0; i < x.length; i++) {
            document.write(x[i].childNodes[0].nodeValue);
        }​

But currently I am only able to fetch one image.

How can I fetch all images instead?


Solution

  • If PHP is an option, have you looked at SimpleXML yet?

    In your case:

        $bracelets_xml = <<<XML
        <bracelets>
                <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" />
                <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" />
                <photo filename="b3.jpg" thumbnail="a3.jpg" description="aa" />
                <photo filename="b4.jpg" thumbnail="a4.jpg" description="aa" />
        </bracelets>
    XML;
        
    $bracelets = new SimpleXMLElement($bracelets_xml);
        
    foreach($bracelets -> photo as $photo) {
        $counter++;
        echo "Photo " . $counter . ":\r\n";
        echo "Filename : " . $photo['filename'] . "\r\n";
        echo "Thumbnail : " . $photo['thumbnail']. "\r\n";
        echo "Description : " . $photo['description']. "\r\n";
    }
        
    

    Obviously the output above isn't what you want, but you could output it however you want depending on the context.