skip to Main Content

for 8 hours now I have been trying to parse this jSON response data

 {"status":"200","message":"Welcome to spakkolos.com! You are welcome. Stay tuned"}    

I have tried the followig, no luck:

$response = wp_remote_request( "https://loopwi.com/json");
$body = wp_remote_retrieve_body($response); 
$json = json_decode($body);
echo $json->message;  //I got NULL
echo $json['message']; // I got NULL

I tried several methods, I explored unserialized function of WordPress – all didn’t work. But this works very excellently perfect outside WordPress. I don’t know why WordPress made this so difficult a simple process!

I have done many research still no straight forward example. Please guys I need your help?
Thanks

2

Answers


  1. Chosen as BEST ANSWER

    Thanks guys for your replies. As @Ajith pointed out regarding trim(); by using

    trim();
    

    function on the response body, the problem solves. There are ways to achieve this:

    $response = wp_remote_request( "https://loopwi.com/json");
    $body = trim(wp_remote_retrieve_body($response), "xEFxBBxBF"); 
    $body = trim($body, "xEFxBBxBF"); 
    $json = json_decode($body);
    echo $json->message; 
    

    Or by this:

    $url = "https://loopwi.com/json";
    $response = wp_remote_get( $url );
    
    if ( is_array( $response ) && ! is_wp_error( $response ) ) {
        $headers = $response['headers']; // array of http header lines
        $body    = trim($response['body'], "xEFxBBxBF"); // use the content
        $json = json_decode($body);
           echo $json->status; 
           echo $json->message;
    }
    

    These are functions in the WordPress WordPress's HTTP API - wp_remote_get, wp_remote_request

    Your project may get rejected if you use file_get_contents() in WordPress. Use the HTTP API functions instead.

    Thanks for all those who answered and commented. Cheers!


  2. Can you try the below code, I have used php file_get_contents instead of wordpress finction, I hope that will make sense to you

    $body = trim(file_get_contents('https://loopwi.com/json'), "xEFxBBxBF");
    $json = json_decode($body);
    echo $json->message;  
    echo $json['message'];
    

    Refer link for explanation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search