2016-09-18 221 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