解析JSON对象并在WordPress php窗口小部件中实时显示

时间:2018-02-02 作者:1976 Umar

我有以下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"
    }
    ]
}
-----------------------------到目前为止,我要测试的代码-------

<?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>\';
}


 }


 }
?>
---------------------------响应-----------

data:
key:status
val:ok
data:
key:totalResults
val:2
data:
key:articles
val:Array
------------------------------我的问题----------------------

是对象还是数组?,我在一个php小部件中显示,但它不断出错

  • 我需要显示所有信息,使用wp remote get-in php小部件实时显示是否安全

  • 1 个回复
    最合适的回答,由SO网友:Maxim Sarandi 整理而成

    您有一个arror,因为您在数组上执行foreach循环,但有一个值也是数组,并且您尝试回显一个数组(articles).

    1. json_decode第二个参数如果为true,则将响应设置为assoc数组,默认情况下返回object

      对数据中的每个数组使用循环。我看到了articles json内部-是数组。

      这是一个不错的做法。但它可能很慢click

    结束

    相关推荐

    wp_send_json erase last value

    我希望你能帮助我。我使用Json将数据从php发送到Javascript。PHPadd_action(\'wp_ajax_myfilter\', \'evenements_filter_function\'); add_action(\'wp_ajax_nopriv_myfilter\', \'evenements_filter_function\'); function evenements_filter_function(){ ....