作者:手机用户2602939543 | 来源:互联网 | 2023-09-16 17:10
我有一个名为processDeleteForm()的PHP函数,用于从名为structure.xml的xml文档中删除指定的节点.到目前为止我遇到的唯一问题是在processDel
我有一个名为processDeleteForm()的PHP函数,用于从名为structure.xml的xml文档中删除指定的节点.到目前为止我遇到的唯一问题是在processDeleteForm()中,它通过循环遍历父节点的每个子节点来搜索要删除的节点,并通过“name”属性匹配它,但是我没有能够为循环获取正确数量的子节点,因此它在到达正确的节点之前就会停止.相关代码:
function processDeleteForm($dir, $filename)
{
echo "Processing delete request.
";
echo "Request to delete ".$filename." from ".$dir.".
";
$xmlDoc = new DOMDocument();
$xmlDoc->load("structure.xml");
$node = dirDOMNodeWritable($dir, $xmlDoc);
$target;
echo "Working directory has ".count($node->childNodes)." child(ren).
";
for($x = 0; $x childNodes); $x++)
{
if($node->childNodes->item($x)->getAttribute("name") == $filename)
{
$target = $node->childNodes->item($x);
echo "Target found.
";
}
else
{
echo "Searching for target...
";
}
}
if($target->getAttribute("type") != "directory")
{
$fstored = "uploads/".$target->childNodes->item(0)->wholeText;
unlink($fstored);
}
$node->removeChild($target);
$file = fopen("structure.xml", "w");
fwrite($file, $xmlDoc->saveXML());
}
structure.xml:
intro.mp3
music.mp3
supersonic.mp3
memories.mp3
chiptek.mp3
intermission.mp3
kicks.mp3
1997.mp3
intro.ogg
music.ogg
supersonic.ogg
memories.ogg
chiptek.ogg
intermission.ogg
kicks.ogg
1997.ogg
*以上应该是xml文件的内容,但我无法弄清楚如何显示它.如果有更多关于在stackoverflow上格式化xml的知识的人可以解决它,我会非常感激.
查看负责创建名为“test01”,“test02”和“test03”的目录的代码可能也很有用:
function processNewForm($dir, $dirName, $readPrivs, $writePrivs)
{
$readString = "";
$writeString = "";
$dirOwner = $_SESSION["user"];
for($x = 0; $x {
$readString += $readPrivs[$x].",";
}
for($x = 0; $x {
$writeString += $writePrivs[$x].",";
}
$xmlDoc = new DOMDocument();
$xmlDoc->load("structure.xml");
$node = dirDOMNodeWritable($dir, $xmlDoc);
$newDir = $xmlDoc->createElement("directory");
$newDir->setAttribute("name", $dirName);
$newDir->setAttribute("owner", $dirOwner);
$newDir->setAttribute("read", $readString);
$newDir->setAttribute("write", $writeString);
$newDir->setAttribute("type", "directory");
$node->appendChild($newDir);
$file = fopen("structure.xml", "w");
fwrite($file, $xmlDoc->saveXML());
}
当前输出如下所示:
Received delete request.
Validating delete request... Request is valid.
Processing delete request.
Request to delete test03/ from /.
Working directory has 1 child(ren).
Searching for target...
Notice: Undefined variable: target in E:\aepi\dev\fileshare.php on line 540
Fatal error: Call to a member function getAttribute() on a non-object in E:\aepi\dev\fileshare.php on line 540
解决方法:
从PHP manual for count():
Returns the number of elements in var. If var is not an array or an object with implemented Countable interface, 1 will be returned.
DOMNode::$childNodes
是DOMNodeList
对象.它不是Countable
.它总会返回一个(即使是空的).请改用其length
财产:
$count = $element->childNodes->length;
更新:从PHP 7.2起,DOMNodeList已成为可数.