0

I have the following as a string:

stdClass Object
(

    [createResult] => stdClass Object

       (
           [ReturnCode] => 1
       )

)

How can I take the above string and create a new stdClass Object? I'd like to get the value like this:

$rc = $obj->createResults->ReturnCode;
1
  • 3
    You want to convert a print_r output into what it used to be? Why? You should probably be using serialization or something... Commented Jan 3, 2012 at 22:42

3 Answers 3

1

If you can change the way it outputs into something like var_export, you can afterwards use that string with eval to get it back.

http://www.php.net/manual/en/function.var-export.php

Sign up to request clarification or add additional context in comments.

2 Comments

This won't work. var_export's dump produces calls to the static method __set_state, which stdClass does not have.
@Charles, indeed it will not work, they are many workarounds, but all of them require some cheating, you can wrap the entire object into another, access all properties and methods... but that is not our case, you could use a parser or something.
1

If you can't change it (for whatever reason) and have to use the output of print_r, then you could try this recipe and see if it works for you. http://www.php.net/manual/en/function.print-r.php#93529

However, if at all possible, you should be storing data in a more portable format. You could use php's serialize => unserialize, or json_encode => json_decode, for starters.

Comments

0

You can also do it like this:

<?php
$s = "stdClass Object
(

    [createResult] => stdClass Object

       (
           [ReturnCode] => 1
  )

)";
$s = preg_match("/\s\[ReturnCode\] => \S+\s/", $s, $m);
echo preg_replace("/\s\[ReturnCode\] => (\S+)\s/", "$1", $m[0]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.