2012-12-08 59 views
0

我的XML文件就像下面..PHP:加載XML文件並獲取節點值

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

我想辦法「座位」節點的值「A2」和「M13」使用PHP。

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

我可以使用上述代碼訪問「名稱」節點。 如何訪問「座位」節點?

回答

1

可以使用的SimpleXML爲:

$xml = simplexml_load_string($xmlContents); 
foreach($xml->student as $student) { 
    echo (string)$student->seat."\n"; 
} 
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; 
}