Search code examples
phpxmlloopsforeachsimplexml

SimpleXML Dynamic Attributes


I'm trying to figure out how to generate the code for this.

$revImages = $revXML->addChild('images');
$revImage = $revImages->addChild('image');
$revImage->addAttribute('src', '001.jpg');

the last line is the static entry for what I need. Is there a foreach statement I can use to auto generate that last line based on the images from a directory so it outputs as such:

<images>
    <image src = "001.jpg"/>
    <image src = "002.jpg"/>
    <image src = "003.jpg"/>
    <image src = "004.jpg"/>
    <image src = "005.jpg"/>
    <image src = "006.jpg"/>
    <image src = "007.jpg"/>
    <image src = "008.jpg"/>
    <image src = "009.jpg"/>
    <image src = "010.jpg"/>
</images>

Solution

  • The solution using glob function (to find pathnames matching a pattern):

    foreach (glob("/path/to/directory/*.jpg") as $filepath) {
        $src = basename($filepath);
        $revImages
           ->addChild('image')
           ->addAttribute('src', $src)
        ;
    }