Pradeeshwar M
Pradeeshwar M

Reputation: 45

How to access Json fields by using php

I am currently working with Accessing json using php in wordpress. I have successfully decoded the json but when i try to access the values it doesn't fetch . I am trying to access the Cluster_ID and Image,Title values. Here's my api link http://ec2-13-127-149-66.ap-south-1.compute.amazonaws.com:5000/api/news

enter image description here

I have tried the following code

<?php

/**

 *Plugin Name: SEC API
 
 **/
function myjson8(){
    $request = wp_remote_get( 'http://ec2-13-127-149-66.ap-south-1.compute.amazonaws.com:5000/api/news' );

if( is_wp_error( $request ) ) {
    return false; // Bail early
}

$body = wp_remote_retrieve_body( $request );

$data = json_decode( $body );

if( ! empty( $data) ) {
    
    foreach($data->NewsFeed->data as $new){
        
        echo $new->Cluster_ID;
        foreach($data->NewsFeed->data->data as $old){
            echo $old->Image;
            echo $old->Title;
        }
    }
    
}
    
}
    

Upvotes: 2

Views: 66

Answers (2)

An Nguyen
An Nguyen

Reputation: 190

The type of NewsFeed is array so It should be $data->NewsFeed[0]->data

Upvotes: 1

rjdown
rjdown

Reputation: 9227

Use the reference you create when looping through the child array.

Instead of foreach($data->NewsFeed->data->data as $old){ you should use this:

foreach($new->data as $old){

Upvotes: 1

Related Questions