2010-03-05 152 views
2

我在學習如何用PHP的簡單XML解析XML。我的代碼是:用PHP的simpleXML解析XML

<?php 
$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\"> <iTunes> myApp </iTunes> </Document>"; 

$xml = new SimpleXMLElement($xmlSource); 

$results = $xml->xpath("/Document/iTunes"); 
foreach ($results as $result){ 
echo $result.PHP_EOL; 
} 

print_r($result); 
?> 

當這運行它返回一個空白屏幕,沒有錯誤。如果我從文檔標記中刪除所有屬性,則返回:

myApp SimpleXMLElement Object ([0] => myApp) 

這是預期結果。

我在做什麼錯?請注意,我無法控制XML源,因爲它來自Apple。

回答

2

有關默認命名空間的部分,請閱讀fireeyedboy's answer。如前所述,如果要在默認名稱空間中的節點上使用XPath,則需要註冊名稱空間。

但是,如果您不使用xpath(),SimpleXML有其自己的魔術可以自動選擇默認名稱空間。

$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\"> <iTunes> myApp </iTunes> </Document>"; 

$Document = new SimpleXMLElement($xmlSource); 

foreach ($Document->iTunes as $iTunes) 
{ 
    echo $iTunes, PHP_EOL; 
} 
+0

太棒了!你能指點我詳細解釋這個功能的文檔嗎? – SooDesuNe 2010-03-06 01:47:44

+0

嗯,就是這樣的事情:就我所知,沒有關於如何處理默認名稱空間的文檔。 – 2010-03-06 16:37:19

0

這條線:

print_r($result); 

是foreach循環之外。也許你應該試試

print_r($results); 

改爲。

0

似乎如果你在xpath上使用通配符(//),它將起作用。此外,不知道爲什麼,但如果您從Document元素中刪除名稱空間屬性(xmlns),您當前的代碼將工作。也許是因爲前綴沒有定義?不管怎樣,下面應該工作:

$results = $xml->xpath("//iTunes"); 
foreach ($results as $result){ 
echo $result.PHP_EOL; 
} 
9

你的XML包含默認命名空間。爲了讓你的xpath查詢起作用,你需要註冊這個命名空間,並且在你正在查詢的每個xpath元素上使用命名空間前綴(只要這些元素都在同一個命名空間下,在你的例子中它們就是這樣):

$xml = new SimpleXMLElement($xmlSource); 

// register the namespace with some prefix, in this case 'a' 
$xml->registerXPathNamespace('a', 'http://www.apple.com/itms/'); 

// then use this prefix 'a:' for every node you are querying 
$results = $xml->xpath('/a:Document/a:iTunes'); 

foreach($results as $result) 
{ 
    echo $result . PHP_EOL; 
}