parse json object and display live in wordpress php widget

I have following json

{
"status": "ok",
"totalResults": 2,
"articles": [
    {
        "source": {
            "id": "cooking-recepie",
            "name": "cooking recepie"
        },
        "author": "cooking recepie Staff",
        "title": "lamb steak",
        "description": "fffffffffffffffffffffff.”",
        "url": "http://www.cooking-recepie.net/node/116605",
        "urlToImage": "https://www.cooking-
recepie.net/sites/default/[type]/[nid]/conte-1801-cap-epa.jpg",
        "publishedAt": "2018-02-02T01:00:00Z"
    },
    {
        "source": {
            "id": "cooking-recepie",
            "name": "cooking recepie"
        },
        "author": "cooking recepie Staff",
        "title": "Igghhhhhhhhhhhhhhhhhhhh?",
        "description": "yhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.",
        "url": "http://www.cooking-recepie.net/116598/inter-push-lautaro-
 martinez",
        "urlToImage": "https://www.cooking-recepie.net/sites/[nid]/Martinez-
 Lautaro-Arg-epa_0_0.jpg",
        "publishedAt": "2018-02-02T01:00:00Z"
    }
    ]
}

—————————–so far my code to test——-

<?php
$request = wp_remote_get( 'https://url' );
if( is_wp_error( $request ) ) {
return false;
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
if( ! empty( $data ) ) {

if (is_array($data) || is_object($data))
{


foreach ($data as $key => $val){
echo 'data:'.$data->$key->$val.'<br>';  
echo 'key:'.$key.'<br>';
echo 'val:'. $val.'<br>';
}


 }


 }
?>

————————-response———–

data:
key:status
val:ok
data:
key:totalResults
val:2
data:
key:articles
val:Array

—————————–my questions ———————-

  1. is it object or array?, i am displaying in a php widget, but it keeps
    on getting error.
  2. i need to display all info
  3. is it safe using wp-remote-get in php widget displaying live?
  4. how to cache the results?

1 Answer
1

You have an arror because you do foreach loop on array, but one of value – also array, and you trying echo an array (articles).

  1. json_decode
    second parametr make your response as assoc array, if true or return object by default

  2. Use loop for each array in your data. I see that articles inside json – is array.

  3. Its not bad practice. But it`s can be slow.
  4. I think this might helps you with cahce troubles: click

Leave a Comment