How to parse SimpleXMLElement in php / Laravel 5?

2019-07-22 05:05发布

问题:

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(); //GuzzleHttp\Client

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 ?

回答1:

The var_dump() output is correct. $xml->StatusCode is a SimpleXMLElement instance. This is of course needed in case you have to, for example, add a child element to it:

$xml->StatusCode->addChild("test", "value");

If $xml->StatusCode contained only the value of the element rather than an instance of SimpleXMLElement, 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:

var_dump($xml->StatusCode); // returns SimpleXMLElement instance
var_dump((string)$xml->StatusCode); // explicitly
var_dump($xml->StatusCode->__toString()); // explicitly, calling the magic function
echo $xml->StatusCode; // implicitly

Some demos



回答2:

 /**
 * @param $xmlObject
 * @param array $out
 * @return array
 */
private function simpleXmlToArray($xmlObject, $out = array ())
{
    foreach ($xmlObject as $index => $node ){
        if(count($node) === 0){
            $out[$node->getName()] = $node->__toString ();
        }else{
            $out[$node->getName()][] = $this->simpleXmlToArray($node);
        }
    }

    return $out;
}