0

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?

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use SimpleXML for that:

$xml = simplexml_load_string($xmlContents);
foreach($xml->student as $student) {
    echo (string)$student->seat."\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.