【问题标题】:Can't GET JSON in wordpress php plugin无法在 wordpress php 插件中获取 JSON
【发布时间】:2015-01-19 17:07:58
【问题描述】:

我正在使用本地安装的 wordpress 测试我在本地构建的 API。

我的 API 路径类似于: http://local.web.tt.com:8615/api/product

当我的节点服务器运行时,当您转到该链接(mongodb 集合对象)时,它会在浏览器中显示此内容:

[
    {
        "_id":"54bd5fbb646174009a450001",
        "productname":"Product 1",
        "overview":"Overview Title",
        "benefits":
            [
                "List item 1",
                "List item 2",
                "List item 3"
            ]
    }
]

我的 PHP wordpress 短代码插件

add_shortcode('product', function($atts, $content) {
    $service_url = 'http://local.web.tt.com:8615/api/product';
    $data = json_decode($service_url, true);

    return $data;
});

当我在博客文章中添加[product] 时,页面上基本上没有显示任何内容。如果我只返回一个简单的字符串,短代码确实有效。

我也试过这个:

add_shortcode('product', function($data) {
    $service_url = 'http://local.web.tt.com:8615/api/product';
    $get = file_get_contents($service_url);
    $data = json_decode($get, true);
    return $data;
});

但是,这只是将Array 吐到短代码所在的位置:

我要做的是捕获 JSON 对象的每个键中的字符串,然后用 HTML 和 CSS 很好地显示它们。即:Benefits array 项目将显示为要点。

基本上是这样的:

$content .='
    <h2>$data.overview</h2>
    <ul>
       <li>$data.benefits[0]
       <li>$data.benefits[1]'

return $content;

知道我错过了什么吗?提前致谢!

【问题讨论】:

  • 您正在尝试通过curl 获取数据,在这种情况下您不需要它,只需json_decode() 即可。
  • 这就是我首先尝试的,但是变得空白......并且没有错误:( 好的将删除帖子的粗略部分,因为这不是必需的
  • 也许你需要return "product = $data";,我不是 wp 专家,但当我读到这一点时:codex.wordpress.org/Function_Reference/add_shortcode
  • 嗯,试过了,还有return "product = {$data['name']}";,但帖子中唯一出现的是字符串product =
  • 应该是$data['benefits'][0]

标签: php json api wordpress


【解决方案1】:
{
"_id": "84b7e4c7946174009a1f0000",
"name": "Name of product",
"overview": "Long blah blah blah blah here...",
"benefits": [
    "List item 1",
    "List item 2",
    "List item 3",
    "List item 4"
]
}

修复你的 json 为键加上引号

 $service_url = 'http://local.web.tt.com:8615/api/product'; 
 $get = file_get_contents($service_url);
 $data = json_decode($get, true);
 return $data;

另外,你为什么要返回数组?

【讨论】:

  • 哦,我现在收到Array!好吧,我想用 CSS 很好地显示所有这些数据。福利数组项目基本上是要点。我也将键更改为带引号,但仍然只是得到Array
  • 噢,我知道了:stackoverflow.com/questions/16700960/… 我现在可以看到页面上的 var_dump 数据正确!很难看,但现在必须格式化...
  • 我更进一步,在这里提出了一个新问题,你认为你有时间来看看吗? stackoverflow.com/questions/28033267/…
猜你喜欢
  • 2019-10-07
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2018-04-28
  • 2017-03-10
相关资源
最近更新 更多