Kiran
Kiran

Reputation: 8538

PHP String Handling

I am getting the response from one of the API calls something like this :

{status: 'true',description: '0617971781'}

I would like to convert into an associative array with ´status´ and ´description´ being the key elements.

I tried the following explode :

explode($str, ",")

But, I am not able to figure out how, still, Is there a quicker way to do it ?

Thanks

Upvotes: 0

Views: 58

Answers (2)

Asenar
Asenar

Reputation: 7020

As said in comments, the string {status: 'true',description: '0617971781'} is not a valid json, but if you can modify the string you get to make it valid, you can use json_decode.

This question can help you to convert the invalid json into a valid one.

// this is a valid json
$json = '{"status": "true","description": "0617971781"}';
$obj = json_decode($json); // 
$array = json_decode($json, true); // force the return type as full array

EDIT: added the 2nd parameter option as suggested by plain jane ;) + added link to change string into valid json

Upvotes: 1

Suvash sarker
Suvash sarker

Reputation: 3170

Your JSON is not a valid JSON.At first make it valid,if you no control on API call then contact with API provider.

Then try something like this:

$json = '{"status": "true","description": "0617971781"}';
$obj = json_decode($json); // 
$array = json_decode($json, true);
print_r($array);

output:

Array ( [status] => true [description] => 0617971781 ) 

Upvotes: 0

Related Questions