skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search