I use Guzzle to make an XML request to an external API in the back-end.
This is where I create the Guzzle client:
$client = new Client(); //GuzzleHttpClient
This is where I make the request:
$request = $client->request( 'GET', 'This is where I put the URL');
This is where I get the Guzzle response and try to parse it:
$xml = $request->getBody()->getContents();
$xml = new SimpleXMLElement($xml);
$xml = simplexml_load_string($xml);
If I do this:
dd($xml);
I receive this in return:
SimpleXMLElement {#240 ?
+"StatusCode": "1"
+"StatusDescription": "Duplicated request"
+"MerchantId": "***"
+"Company": "***"
+"CompanyCity": "***"
+"CompanyPhone": "***"
+"CompanyDbaName": "***"
+"Balance": "99965"
+"TransDate": "2017-10-07"
+"TransTime": "06:58:48"
+"ProductVer": "***"
+"PromoVer": object
+"SoftVer": object
+"InvoiceNumber": object
}
My problem is that I don't know how to parse this. I want to get the 1
in StatusCode
.
If I do this:
dd($xml->StatusCode);
I receive this:
SimpleXMLElement {#242 ?
+0: "1"
}
How do I get just 1
?
The
var_dump()
output is correct.$xml->StatusCode
is aSimpleXMLElement
instance. This is of course needed in case you have to, for example, add a child element to it:If
$xml->StatusCode
contained only the value of the element rather than an instance ofSimpleXMLElement
, you wouldn't be able to do any modifications on the loaded XML.So, what you need to do, is cast the value of
StatusCode
to a string. There are various ways of doing this:Some demos