My goal is: first, find a specific key in an XML file. Second, return the parent of the key. In the code example below, the key is a filename.
Code:
<?php
$inputXML = simplexml_load_file("data.xml");
$myProject = lookupProject($inputXML, "file1");
echo $myProject->projectname; //print the name of the project containing <filename>"file1"</filename>
echo "\n";
/*
Goal: return the <project> that is the parent of <filename>$input_filename</filename>
Assume: a <filename> appears in at most one <project> subtree.
*/
function lookupProject($myXML, $input_filename)
{
foreach($myXML->project as $curr_project) //notice I don't mention the root <projects></projects>
{
foreach($curr_project->filename as $curr_filename)
{
if ($curr_filename == $input_filename)
{
return $curr_project;
}
}
}
return null; //if not found, return null
}
?>
Example data file, data.xml
<projects>
<project>
<projectname>project1</projectname>
<filename>file1</filename>
<filename>file2</filename>
</project>
<project>
<projectname>project2</projectname>
<filename>file3</filename>
</project>
</projects>
If we have a more complex XML structure with many levels of subtrees, finding the parent of file1 could require lots of foreach() loops. Is there a SimpleXML command that would abstract away the loops that appear in lookupProject?
tl;dr is there a short/elegant (one-line?) solution that implements lookupProject()?
Note that this is homework, but the above question is not at all the crux of the homework problem. I’m done with the homework assignment, but knowing the answer to the above question would help me to make my solution more elegant.
The more appropriate term for “key” would be “TextNode value”. You are looking for
SimpleXMLElement::xpath— Runs XPath query on XML dataIn your case this XPath query will give the projectname element
Since this is tagged homework, I’ll leave it up to you to figure out the necessary PHP code.