Home > Enterprise >  Can't get basic remote API value shown in PHP
Can't get basic remote API value shown in PHP

Time:10-24

This is my code, where I am trying to show the values from the remote API which I am trying to fetch via a .php file in Wordpress.

<?php 

try {
    $response = wp_remote_get( 'MYURLHERE', array(
        'headers' => array(
            'Accept' => 'application/json',
        )
    ) );
    if ( ( !is_wp_error($response)) && (200 === wp_remote_retrieve_response_code( $response ) ) ) {
 $result =  json_decode( wp_remote_retrieve_body( $response, true) );
 echo $result['data']['0']['id'];

    }
} catch( Exception $ex ) {
    //Handle Exception.
}

?>

Getting the following error:

Fatal error: Uncaught Error: Cannot use object of type stdClass as array

What am I doing wrong?

This should be the array:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [id] => 124
                    [name] => MyName
                    [supertype] => Mso

CodePudding user response:

In PHP manual, you can see the parameters of JSON Function: https://www.php.net/manual/en/function.json-decode.php

This json_decode line of code is wrong, here's the fix:

$result =  json_decode( wp_remote_retrieve_body( $response), true );

CodePudding user response:

You must be outputting a different variable than the one you are getting a error for.

This is because you use json_decode() without any parameters. This means it will be outputted as an object, not an array.

So the example output you show must originate from some other place than the $result you are trying to echo.

  • Related