Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get basic remote API value shown in PHP

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This should be the array:

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

>Solution :

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 );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading