tags:

views:

95

answers:

3

Hi,

I would like to know how one can write PHP code to read filenames from a particular folder and save the extracted filenames in an XML document?

An example of any part of this would be HIGHLY appreciated.

Thanks

+1  A: 

Modify the code example found at readdir() manual a bit, and you're done! Something like this could work:

<?php
$out="<FileList>\n";
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $out.='<file>'.$file."</file>\n";
        }
    }
    closedir($handle);
}
$out.='</FileList>';
file_put_contents("./outfile.xml",$out);
?> 
naivists
A: 

Start looking at "glob" for reading the filenames of a directory: http://php.net/manual/de/function.glob.php work yourself through array-manipulation and look at the file-manipulation functions afterwards: http://www.php.net/manual/de/function.file-put-contents.php.

Leonidas
+4  A: 

I would recommend using SimpleXML rather than handcrafting your XML. You don't want your system to choke whenever someone uses special characters in file names.

$out = simplexml_load_string('<files />');

$DI = new DirectoryIterator('/path/to/dir');
foreach ($DI as $file)
{
    if ($file->isFile())
    {
        $out->addChild('file', $file->getFilename());
    }
}

$out->asXML('files.xml');
Josh Davis
Yes! Concatenated XML is da debil.
Lucas Oman
`isDot` will not omit directories though. 'isFile' would be a better check.
Gordon
Yeah, I didn't realize that the OP would want to omit directories but it makes sense.
Josh Davis