如何使用DOMDocument方法获取xml子元素的值?

时间:2011-06-01 02:35:10

标签: php xml

我是PHP和XML的新手。

有人可以告诉我如何获取xml元素的子元素或子节点的值?

index.php

$domdoc = new DOMDocument(); 
$domdoc->load('actionstars.xml'); 

foreach ($domdoc->getElementsByTagName("actionstar") as $star) {
 echo $star->item(0)->nodeValue; // displays the <id> element
 echo $star->item(1)->nodeValue; // displays the <name> element
 echo "<br />";
} 


actionstars.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<actionstars>
 <actionstar>
  <id>1</id>
  <name>Jean Claude Van Damme</name>
 </actionstar>
 <actionstar>
  <id>2</id>
  <name>Scott Adkins</name>
 </actionstar>
 <actionstar>
  <id>3</id>
  <name>Dolph Ludgren</name>
 </actionstar>
 <actionstar>
  <id>4</id>
  <name>Michael Jai White</name>
 </actionstar>
 <actionstar>
  <id>5</id>
  <name>Michael Worth</name>
 </actionstar>
</actionstars>

请帮忙......

1 个答案:

答案 0 :(得分:3)

如果您可以保证他们的订单,您可以使用childNodes和偏移量,否则......

$domdoc = new DOMDocument(); 
$domdoc->load('actionstars.xml'); 

foreach ($domdoc->getElementsByTagName("actionstar") as $star) {
 echo $shit->getElementsByTagName('id')->item(0)->nodeValue; // displays the <id> element
 echo $shit->getElementsByTagName('name')->item(0)->nodeValue; // displays the <name> element
 echo "<br />";
}