Jump to content

XML Parse trouble


wglenn01

Recommended Posts

Hi all, need some quick help i'm working on a cart script with Mercury Payments, their "initializePayment" system throws this XML back to me but for some reason I cannot figure out how to parse it to grab the PaymentID out of it. Any clues? I've been playing with SimpleXML for about the last 6 hours before I gave up.


Thanks a ton!

 

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><InitializePaymentResponse xmlns="http://www.mercurypay.com/"><InitializePaymentResult><ResponseCode>0</ResponseCode><PaymentID>8f19cc14-27fc-40ec-a929-bee4f043387f</PaymentID><Message>Initialize Successful</Message></InitializePaymentResult></InitializePaymentResponse></soap:Body></soap:Envelope>


William

Link to comment
https://forums.phpfreaks.com/topic/275650-xml-parse-trouble/
Share on other sites

The key part that you are missing is likely the use of SimpleXMLElement::children() to access elements under different namespaces.  You have two namespaces to deal with; one for SOAP, and one for Mercury.

 

The general idea is that children() selects children (weird, huh!) and you can specify the XML namespace that those children should belong to by prefix or URI.

 

$envelope = simplexml_load_string('…');

$payment_id = (string) $envelope->children('soap', true)
                                ->Body
                                ->children('http://www.mercurypay.com/')
                                ->InitializePaymentResponse
                                ->InitializePaymentResult
                                ->PaymentID;

echo $payment_id;

 

This will print out 8f19cc14-27fc-40ec-a929-bee4f043387f with your XML.

 

Navigating through the XML structure like that can be long-winded: it is often a little neater to use XPath to get an array of the elements you're interested in.

 

$envelope = simplexml_load_string('…');

$envelope->registerXPathNamespace('mercury', 'http://www.mercurypay.com/');

// xpath() returns an array, even if only one element matches
$payment_ids = $envelope->xpath('descendant::mercury:PaymentID');
$payment_id = (string) $payment_ids[0];

echo $payment_id;

 

Or, you could use a regular expression match. :shy:

 

 

Helpful links

Link to comment
https://forums.phpfreaks.com/topic/275650-xml-parse-trouble/#findComment-1418681
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.