我正在尝试使用PHP将子注释添加到XML文件中。我以前使用过相同的方法大约5次,每个方法都按预期工作,但是这个方法在新文件上使用了不同的xml结构(我认为这可能是问题的一部分)。
导致我这个问题的方法是:
function addCourseToProject($name, $project){
$projects = self::getRoles();
$theProject = $projects->xpath('project[name = "'.$project.'"]');
echo $theProject->name;
$theCourses = $theProject[0]->courses->addchild("course", $name);
$projects->asXml("projects.xml");
}
XML文件如下所示:
<projects>
<project>
<name>Alpha</name>
<courses>
<course>Beta</course>
<course>Charlie</course>
</courses>
</project>
</project>
getRoles()
看起来像这样:
function getRoles(){
$roles = simplexml_load_file("projects.xml") or die("ERROR: Unable to read file");
return $roles;
}
我在这里不知所措,我不知道为什么这与其他添加功能不同(见下文)。
如果有人能提供一些帮助我会很感激:)
我的其他方法的示例:
function addModule($courseName, $name, $link){
$xml = self::getXml();#get the xml file
$course = $xml->xpath('course[name = "'.$courseName.'"]');
$module = $course[0]->addChild("module");
$module->addChild("name", $name);
$module->addChild("link", $link);
$xml->asXml("data.xml");
echo self::toJSON($course);
}
和getXML()
方法:
function getXml(){
$xml=simplexml_load_file("data.xml") or die("ERROR: Unable to read file");
return $xml;
}
答案 0 :(得分:1)
原来这个问题是由于<project>
元素嵌套在XML文档中引起的。您可以使用descendant-or-self
轴(//
作为缩写语法)来获取嵌套元素,如下所示:
$theProject = $projects->xpath('//project[name = "'.$project.'"]');
或指定完整路径:
$theProject = $projects->xpath('/projects/project[name = "'.$project.'"]');