0

我的 xml 文件如下所示..

<CA>
  <student>
    <name>james</name>
    <seat>A2</seat>
  </student>
  <student>
    <name>Asada</name>
    <seat>M13</seat>
  </student>
</CA>

我想使用 PHP 接近“座位”节点的值“A2”和“M13”。

$root = $xml->documentElement;
$current = $root->firstChild;
$test = $current->firstChild;

我可以使用上面的代码访问“名称”节点。如何访问“座位”节点?

4

2 回答 2

4

您可以为此使用 XPath:

$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;
}
于 2012-12-08T15:39:25.957 回答
2

您可以为此使用 SimpleXML:

$xml = simplexml_load_string($xmlContents);
foreach($xml->student as $student) {
    echo (string)$student->seat."\n";
}
于 2012-12-08T15:34:39.147 回答