0

I'm receiving this response from a server when I put print_r($response):

    {"success":true,"title_response":"SUCCESS","text_response":"any text"}}

I have tried use:

     list($var1, $var2,$var3)=explode(",", $response);

but result is:

     $var1= {"success":true;
     $var2= "title_response":"SUCCESS";
     $var3= text_response":"any text"}};

I need the result:

    $var1= true;
    $var2= "SUCCESS";
    $var3= "any text";

Any idea?

3
  • not really an answer but this should help php.net/manual/en/function.trim.php Commented Feb 8, 2017 at 18:41
  • It's a json_encoded string (mostly. There's an extra brace, could be a pasting issue?). Use json_decode to get the data out. Commented Feb 8, 2017 at 18:42
  • @aynber It is NOT a valid json_encoded string. The { } are unbalanced. (Unless that is an typo in the question post.) Commented Feb 8, 2017 at 18:43

2 Answers 2

2

It's a JSON string, you can use a combination of json_decode to convert to an object and then get_object_vars to get the object's variables as an array:

list($var1, $var2, $var3) = get_object_vars(json_decode($response));

echo $var2;   // SUCCESS

As noted in the comments, this will only work if the string is valid JSON. I'm assuming a copy/paste error when writing the question, and that you do have valid JSON.

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

2 Comments

Thanks for your response, i received this error: Notice: Undefined offset: 2 in C:\xampp\htdocs\elyo\date.php on line 179
@HernánDavidGómezS date.php? I don't see how that's related to this answer.
0

You can parse it as follows:

// Problem data (with unbalanced { }'s)
$response = '{"success":true,"title_response":"SUCCESS","text_response":"any text"}}';

// Remove trailing '}}'
$response = substr($response, 0, -2);

// Split on the commas
$temp = explode(',', $response);

// For each element in the array, split on the colon, and take second part
array_walk($temp, function(&$value) {
  $value = explode(":", $value)[1];
});

// Distribute array into your variables
list($var1, $var2, $var3) = $temp;

But this is very fragile code. If your strings have commas or colons in it, it will break in various fashions.

It is better to get a valid JSON response, and parse it using the proper JSON functions, as explained by @Madbreaks.

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.