简体   繁体   中英

How to parse stdClass object?

I have a SOAP response whose var_dump looks like this:

object(stdClass)[14]
  public 'GetClientsResult' => 
    object(stdClass)[15]

I can't figure out how to parse this for the life of me, I've never used stdClass before.

How can I parse this response in PHP?

For starters, you can cast it into an array (assuming the object is stored in $response ):

$response = (array) $response;

Or you can access things by:

$response->GetClientResult->otherStuff;

An StdClass is an empty class where you can set and get property values. An example:

 <?php
 // $response is a normal array
 $response['GetClientResult'] = 'foo'; // set
 $response['GetClientResult']; // get

 // $response is a StdClass
 $response->GetClientResult = 'foo'; // set
 $response->GetClientResult; // get
 ?>

And if you want to cast the class back to an array you can use:

$response = (array) $response

And if you want to do that recursive, because you have multiple StdClasses:

function StdClass2array(StdClass $class)
{
    $array = array();

    foreach ($class as $key => $item)
    {
            if ($item instanceof StdClass) {
                    $array[$key] = StdClass2array($item);
            } else {
                    $array[$key] = $item;
            }
    }

    return $array;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM