我对在PHP中解析XML感到困惑

时间:2011-05-20 16:53:18

标签: php xml parsing

如何使用PHP解析XML数据?我想获得名为

的元素的内容
<profile xmlns="mysite.com">
 <confirmationNumber>128686132</confirmationNumber>
 <merchantRefNum>123456</merchantRefNum>
 <customerEmail>test@test.com</customerEmail>
</profile>

我试图使用此代码

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

但我不知道如何选择特定元素。

6 个答案:

答案 0 :(得分:3)

您不需要SimpleXML的遍历方法。只需使用simplexml_load_string(),如果您已经将其放在一个中:

$xml = simplexml_load_string($decodedMessage);

然后访问内容为 simple

print $xml->customerEmail;

答案 1 :(得分:1)

您可以尝试使用函数simplexml_load_file(),并使用XML作为对象。或转换为带有强制转换的数组。

答案 2 :(得分:0)

你应该看看xpath

答案 3 :(得分:0)

处理它的最简单方法之一是在google上寻找一个名为xml2array的函数,因为关联数组在PHP中比XML更容易处理。

答案 4 :(得分: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;

答案 5 :(得分:0)

如果要在较大的文档中找到一个元素,可以使用XPath

例如,对于XML

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

您可以简单地执行$sxe->xpath('//profile'),它将返回文档中所有配置文件元素的数组(作为SXE,然后您可以处理它们)。如果只有一个配置文件元素,那么你已经完成了,但如果有很多,你将需要一个更具体的XPath。