Search code examples
phpxmllistjpeg

PHP - folders list to xml


Truth to be said i dont know where to begin with. This is a given situation:

I have default xml list that looks like this:

<list>
    <cat>
        <l1>parent</l1>
        <l2>child</l2>
        <l2>child</l2>
    </cat>
    <cat>
        <l1>parent</l1>
        <l2>child</l2>
        <l2>child</l2>
    </cat>
</list>

and i have all those child folders on server in the same level so theres no depth. Each child contains number pf JPG images.

Now what i need to make is a PHP that creates the same structured xml but with aditional number of currently containing JPG's next to each childs name and set apropriate cumulative number to their parent name.

Any ideas?


Solution

  • Assuming that you need a script located on a certain root-path to scan for all containing folders and files (jpg's), then this php-script might help you:

    <?php
    
    $currDirPos = "./";
    
    function createCats($currDirPos, $level=1){
        $result = [];
    
        if(is_dir($currDirPos)){
            foreach (scandir($currDirPos) as $subDir) {
                // do not take ./ ../ or own script-name into consideration
                if($subDir=="."||$subDir==".."||$subDir==basename(__FILE__))continue;
                $entry = ["name"=>$subDir,"level"=>$level];
                if(is_dir($currDirPos."/".$subDir)){
                    $entry["children"] = createCats($currDirPos."/".$subDir,$level+1);
                }
                $result[] = $entry;
            }
        }
    
        return $result;
    }
    
    function createXMLOutOfCatArray($cats){
        $xml = "<list>";
        function reduceToItemEntities($parent){
            $output = "";
            if(isset($parent["children"])){
                foreach ($parent["children"] as $listItem) {
                    $output .= "<l".$listItem["level"].">".$listItem["name"]."</l".$listItem["level"].">";
                    $output .= reduceToItemEntities($listItem);
                }
            }
            return $output;
        }
        foreach ($cats as $cat) {
            $xml .= "<cat>";
            $xml .= "<l".$cat["level"].">".$cat["name"]."</l".$cat["level"].">";
            $xml .= reduceToItemEntities($cat);
            $xml .= "</cat>";
        }
        return $xml."</list>";
    }
    
    header('Content-Type: text/xml');
    echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . createXMLOutOfCatArray(createCats($currDirPos));
    ?>
    

    It basically makes use of the function scandir to get all folder and file names in the function createCats. createCats creates an array that contains all cat-elements and it's children in a hierarchical order.

    The createXMLOutOfCatArray is then used to convert the former fetched folder/files names into a xml-structure.

    Hope this helps you.