1

I am having this issue where wp_remote_get appears to be adding backslashes "\" to my string. It also adds things in like body and headers.

{"headers":{},
"body":" {\"page\":1,\"total_results\":44,\"total_pages\":3,\"results\": [{\"vote_count\":7398,\"id\":299536,\"video\":false,\"vote_average\":8.3,\"title\":\"Avengers: Infinity War\",\"popularity\":220.311,\"poster_path\":\"\\/7WsyChQLEftFiDOVTGkv3hFpyyt.jpg\",\"original_language\":\"en\",\"original_title\":\"Avengers: Infinity War\",\"genre_ids\":

If I use a curl however I get the following string. This is what I want my string to look like.

{"page":1,"total_results":44,"total_pages":3,"results":[{"vote_count":7398,"id":299536,"video":false,"vote_average":8.3,"title":"Avengers: Infinity War","popularity":220.311,"poster_path":"\/7WsyChQLEftFiDOVTGkv3hFpyyt.jpg","original_language":"en","original_title":"Avengers: Infinity War","genre_ids":

Any help is appreciated.

2
  • Try to apply stripslashes() on the response body. E.g.: $body = stripslashes( $body );
    – Sally CJ
    Commented Sep 1, 2018 at 0:04
  • Thanks for the help Sally, turns out it was due to something else but thank you for the help I appreciate it.
    – Dev john
    Commented Sep 1, 2018 at 16:05

1 Answer 1

1

wp_remote_get() returns an array containing the response headers and the response body. When you json_encode() the response, which you appear to have done, then the body is going to be escaped so that it doesn't break the JSON it thinks you're trying to create. You're adding the slashes when you do this.

To get the body of the response you need to then use wp_remote_retrieve_body(). Then to turn the JSON into an array, you need to use json_decode():

$request = wp_remote_get( $url );
$response = wp_remote_retrieve_body( $request );

var_dump( json_decode( $response ) );
1
  • Thank you for the help Jacob, I really appreciate. Can't believe it was such a silly mistake on my part. I didn't realise it automatically did headers and the response body, I probably should have read the documentation more carefully. Anyway sorry for the rant.
    – Dev john
    Commented Sep 1, 2018 at 16:04

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.