2011-05-20 43 views
1

如何使用PHP解析XML數據?我想不僅僅是元素的內容命名我對PHP中解析XML感到困惑

<profile xmlns="mysite.com"> 
<confirmationNumber>128686132</confirmationNumber> 
<merchantRefNum>123456</merchantRefNum> 
<customerEmail>[email protected]</customerEmail> 
</profile> 

我嘗試使用此代碼

$sxe = new SimpleXMLElement($decodedMessage); 
echo $sxe->getName() . "\n"; 
foreach ($sxe->children() as $child) 
{ 
echo $child->getName() . "\n"; 
} 

但我不知道如何選擇一個特定的元素。

回答

3

您不需要SimpleXML的遍歷方法。只要使用simplexml_load_string()如果你已經擁有它的一個:

$xml = simplexml_load_string($decodedMessage); 

然後訪問該內容爲簡單爲:

print $xml->customerEmail; 
0

一個對付它的最簡單的方法是找一個功能在google上稱爲xml2array,因爲關聯數組在PHP中比在XML中處理起來要容易得多。

0

你可以試試這個。

$xml = simplexml_load_file($filePath) or die ("Unable to load XML file!"); 
//Access XML Data 
echo "confirmation Number: " . $xml->confirmationNumber; 
echo "merchant Ref Num: " . $xml->confirmationNumber; 
echo "customer Email: " . $xml->customerEmail; 
0

如果你想找到一個更大的文檔中的一個元素,你可以使用XPath

例如,對於XML

<some> 
    <hierarchy> 
    <profile> 
     <etc>et cetera</etc> 
    </profile> 
    </hierarchy> 
</some> 

,你可以簡單地做$sxe->xpath('//profile'),這將返回所有型材件文檔中隨處可見的陣列(如SXEs,您可以再處理)。如果只有一個配置文件元素,那麼你就完成了,但是如果有很多,你需要一個更具體的XPath。