Stanley Ngumo
Stanley Ngumo

Reputation: 4239

Reading filenames in a folder and storing them in XML using PHP?

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

Upvotes: 1

Views: 890

Answers (3)

Leonidas
Leonidas

Reputation: 2438

Start looking at glob() for reading the filenames of a directory. Work yourself through array-manipulation and look at the file-manipulation functions afterwards: file_put_contents

Upvotes: 0

Josh Davis
Josh Davis

Reputation: 28730

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');

Upvotes: 4

naivists
naivists

Reputation: 33501

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);
?> 

Upvotes: 1

Related Questions