PHP:加载xml文件并获取节点值

时间:2012-12-08 15:21:21

标签: php xml

我的xml文件如下所示..

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

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

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

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

您可以使用SimpleXML:

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