Skip to content
Advertisement

Cannot add child to XML node in PHP

I am trying to add a child note to an XML file using PHP. I have used the same method about 5 times before and each one works as expected, however this method is using a different XML structure on a new file (which I think might be part of the problem).

The method causing me the problem is this:

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

}

The XML file looks like this:

<projects>
    <project>
        <name>Alpha</name>
            <courses>
                <course>Beta</course>
                <course>Charlie</course>
            </courses>
    </project>
</project>

And getRoles() looks like this:

function getRoles(){
     $roles = simplexml_load_file("projects.xml") or die("ERROR: Unable to read file");
return $roles;
}

I’m at a loss here, I have no idea why this is different from the other adding functions (see below).


Should you need it, here is an example of what my other methods look like:

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

and the getXML() method:

function getXml(){
     $xml=simplexml_load_file("data.xml") or die("ERROR: Unable to read file");
    return $xml;
}

Advertisement

Answer

Turned out that the problem was caused by the fact that <project> element is nested within the XML document. You can use descendant-or-self axis (// for the abbreviated syntax) to get nested element like so :

$theProject = $projects->xpath('//project[name = "'.$project.'"]');

or specify the complete path :

$theProject = $projects->xpath('/projects/project[name = "'.$project.'"]');
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement