Reputation: 473
My xml file is like below..
<CA>
<student>
<name>james</name>
<seat>A2</seat>
</student>
<student>
<name>Asada</name>
<seat>M13</seat>
</student>
</CA>
And I want to approach "seat" node's value "A2"and "M13" using PHP.
$root = $xml->documentElement;
$current = $root->firstChild;
$test = $current->firstChild;
I can access "name" node using above code. How can I access "seat" node?
Upvotes: 0
Views: 6709
Reputation: 496
you can use XPath for that:
$xml = <<<END
<CA>
<student>
<name>james</name>
<seat>A2</seat>
</student>
<student>
<name>Asada</name>
<seat>M13</seat>
</student>
</CA>
END;
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
$entry = $xpath->query("//CA/student/seat");
foreach($entry as $ent){
echo $ent->nodeValue;
}
Upvotes: 4
Reputation: 4404
You can use SimpleXML for that:
$xml = simplexml_load_string($xmlContents);
foreach($xml->student as $student) {
echo (string)$student->seat."\n";
}
Upvotes: 2