0
下面是一段代码,我一直在努力使其最近工作。不幸的是,它不工作,因为我希望它。
以下代码应该查看“图库”文件夹,找到其中的任何文件和文件夹,并将所有输出存储到xml文件中。
我期望XML文件应该是这样..
<categories>
<movies>
file1.jpg
file2.jpg
</movies>
<games>
file1.jpg
</games>
</categories>
等等...
但我下面的代码返回我这个输出,而不是:
<?xml version="1.0"?> <Categories/>
这里是代码
<?php
class XML_file
{
private $doc;
private $root;
private $MyXml_file_handler;
private $node;
private $child;
public function __construct($root_name, $file)
{
$this->MyXml_file_handler = fopen($file, 'w') or die('Cannot open file: '.$file); //implicitly creates file
$this->doc = new DOMDocument('1.0');
$this->node = new DOMText;
$this->doc->formatOutput = true;
$this->root = $this->doc->createElement($root_name);
$this->root = $this->doc->appendChild($this->root);
echo __CLASS__," has been created. <br />";
}
public function __destruct()
{
fwrite($this->MyXml_file_handler, $this->doc->saveXML());
fclose($this->MyXml_file_handler);
echo __CLASS__," has been destroyed. <br />";
}
public function AppendChild($name)
{
$this->child = $this->doc->createElement($name);
$this->child = $this->node->appendChild($this->child);
}
public function CreateNode($content)
{
$this->node = $this->doc->createTextNode($content);
$this->node = $this->root->appendChild($this->node);
}
}
class ImageDb
{
////// Constructor & Destructor //////////////////
private $myXML;
public function __construct($dir)
{
$this->myXML = new XML_file("Categories","myImageDB.xml");
$this->SearchDir($dir);
echo __CLASS__," has been created. <br />";
}
public function __destruct()
{
echo __CLASS__," has been destroyed. <br />";
}
////// Constructor & Destructor //////////////////
function SearchDir ($dir)
{
if($dh = opendir($dir))
{
while (false !== ($filename = readdir($dh)))
{$files[] = $filename;}
rsort($files);
foreach ($files as $key => $value)
{
if (!in_array($value,array(".","..")))
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
{
$this->myXML->AppendChild($value);
echo "Directory: $value <br />";
$this->SearchDir("$dir$value");
}else {
$this->myXML->CreateNode($value);
echo "File: $value <br />";
}
}
}
closedir($dh);
}
}
}
$image = new ImageDb("../galeria/");
?>
我无法弄清楚问题出在哪里。
我确定它确实找到了该文件夹中的所有文件,并且它还在屏幕上打印了所有 内容,但是当我尝试将内容存储到xml文件时它不起作用。
/////////编辑/////
我现在已经修改了XML_FILE类内的两个功能,它的返回这一点。
<?xml version="1.0"?> <Categories>filex.txt<Space/><Nature/><Movies/>file2.txtfile1.txt<Games/></Categories>
public function AppendChild($name)
{
$this->child = $this->doc->createElement($name);
$this->child = $this->root->appendChild($this->child);
}
public function CreateNode($content)
{
$this->node = $this->doc->createTextNode($content);
$this->node = $this->root->appendChild($this->node);`
}
正如你所看到的,它现在只打印了 “封闭” 的元素。 所以现在我只需要了解它为什么不添加“开放”元素。
任何帮助将不胜感激,
在此先感谢,亚历克斯