读取文件夹中的文件名并使用PHP将它们存储在XML中?

问题描述:

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

我想知道如何编写PHP代码以从特定文件夹中读取文件名并将提取的文件名保存在 一个XML文档? p>

很高兴赞赏这一部分的一个例子。 p>

谢谢 p> div>

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

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

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

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