2016-09-18 68 views
-1

我的XML文件的example.xml如下:XML解析使用PHP使用simplexml_load_file

<?xml version="1.0" encoding="UTF-8"?> 
<Declaration> 
     <ID>345678</ID> 
     <TransID>1473909194263</TransID> 
    <Time>2016-02-24T22:13:15</Time> 
<Groups> 
    <Group> 
    <Name>Aaron</Name> 
     <SelectedFields/> 
    </Group> 
</Groups> 
<Scores/> 
    <RelatedVariables> 
     <RelatedVariable dataType="Number"> 
     <Value>5555</Value> 
     </RelatedVariable> 
     <RelatedVariable dataType="Number"> 
     <Value>9999</Value> 
     </RelatedVariable> 
    </RelatedVariables> 
</Declaration> 

我的PHP代碼如下:

$xml=simplexml_load_file("example.xml") or die("Error: Cannot create object"); 

echo $xml->ID;      //Gives 345678 

echo $xml->Groups->Group->Name;  // Gives Group->Name rather than Aaron 

問:
當我使用PHP simplexml_load_file方法獲取值$ xml-> ID 由上面的代碼它給了345678.但是,當我試圖得到的價值 $ x ml-> Groups-> Group->將解析器命名爲困惑並給出 Group-> Name而不是給予Aaron。解析器與 組和我想的混淆。什麼是正確的代碼,以獲得名稱亞倫

+0

的[你如何解析和PHP程序的HTML/XML?(可能的複製http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html- xml-in-php) – ThW

+0

Hi Thw我的問題與上面提出的問題不同 – Explorer

+0

無法重現您的問題。我當然會在第三線獲得*亞倫*。 – Parfait

回答

0

我們試圖重現您的問題,但仍然獲得第三線亞倫。 如果你仍然面臨同樣的問題,請檢查下面的代碼,它會解決你的問題。

$xml=simplexml_load_file("example.xml") or die("Error: Cannot create object"); 
$xml = json_decode(json_encode($xml),true); 
echo $xml['ID']; //Gives 345678 
echo $xml['Groups']['Group']['Name']; //Gives Aaron