开发者

I'm confused about parsing XML in PHP

How can I parse XML data using PHP? I want to get the contents of just the element named

<profile xmlns="mysite.com">
 <confirmationNumber>128686132</confirmationNumber>
 <merchantRefNum>123456</merchantRefNum&g开发者_如何学Got;
 <customerEmail>test@test.com</customerEmail>
</profile>

I was trying to use this code

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

But I don't know how to select a specific element.


You don't need the traversal methods of SimpleXML. Just use simplexml_load_string() if you already have it in one:

$xml = simplexml_load_string($decodedMessage);

Then accessing the content is as simple as:

print $xml->customerEmail;


You can try the function simplexml_load_file(), and use the XML as object. Or convert to array with cast.


You should look at xpath.


One of the easiest ways to deal with it is look for a function on google called xml2array, since associative arrays are much easier to deal with in PHP than XML.


you can try this.

$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;


If you want to find that one element within a larger document, you could use XPath.

For example, for the XML

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

you can simply do $sxe->xpath('//profile'), which will return an array of all the profile elements everywhere in the document (as SXEs, which you can then process). If there is only one profile element, then you're done, but if there are many you will need a more specific XPath.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜