1
 //...snip..
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;

The response of a php curl request is showing as

"{\"result\":\"success\",\"entry\":\"22\",\"confirm\":\"yes\"}"

However, the output should not have \ in front of the quotes. How do I remove those quotes and return as proper JSON

{
"result":"success",
"entry":"22",
"confirm":"yes"
}

Few options I tried are return print_r($result). This is returning as expected, but I think this is not proper way.

PHP version - 5.6.16

3 Answers 3

2

Your output is correct and you have valid json; which is a string.

All you have to do, is decode it:

$s = "{\"result\":\"success\",\"entry\":\"22\",\"confirm\":\"yes\"}";

var_dump(json_decode($s));

An example.

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

5 Comments

But json_decode removes keys like result, entry, confirm.
@blakcaps What do you mean, have you checked the example? It returns an object with the keys result, entry, etc.
@blakcaps yes jeroen is right .. it returns an object with keys only .. please check.
I am trying to return the $result from a method. How can I use var_dump for method return
@blakcaps The var_dump() was just to show the results, if you need an object (or array...), just return the result of json_decode().
1

You can use stripslashes() to remove slashes from the JSON String then decode the JSON String using json_decode().

Like this,

$json_string="{\"result\":\"success\",\"entry\":\"22\",\"confirm\":\"yes\"}";
$json_string=stripslashes($json_string);
$json_array=json_decode($json_string,true);
print_r($json_array);

Above method just remove the slashes from the string and uses json_decode() to decode the JSON String.

But you can also decode the string directly with the slashes. (Thanks to @jeroen) Like this,

$json_string="{\"result\":\"success\",\"entry\":\"22\",\"confirm\":\"yes\"}";
$json_array=json_decode($json_string,true);
print_r($json_array);

Second parameter in json_decode() denotes you want to parse the JSON String in array instead of object which is default behavior.

2 Comments

There is no need to use stripslashes(), you can decode this directly.
Its true, stripslashes not required. If you add stripslashes json string will break
0

Simply use following header option in your curl, will return json object:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

Because default accept type is Text/Plain so it will return you parsed sting. By setting above header you will receive json object.

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.