【问题标题】:How to transfer json data to html with php?如何使用 php 将 json 数据传输到 html?
【发布时间】:2011-01-08 23:22:08
【问题描述】:

如何用php将json数据转成html?

$url="http://api.nytimes.com/svc/search/v1/article?format=json&query=usa&rank=newest&api-key=mykey"

当我在浏览器中输入网址时,它会返回 {"offset" : "0" , "results" : [{"body" : "A guide to cultural and recreational goings-on in and around the Hudson Valley. ...}]} 如何将 json body 数据放入 html?我的意思是这样echo '<div class="body"></div>';

【问题讨论】:

  • 您从哪里调用 URL?客户端(JavaScript)还是服务器端(PHP)?
  • 你的问题实在是太模糊了,能不能展开说一下?

标签: php json


【解决方案1】:

您首先需要获取文件。您应该为此使用 curl。在下面的示例中,我使用了 file_get_contents() 函数,您可能想要替换它。使用json_decode() 为您解析 JSON。

$json = file_get_contents($url);
$data = json_decode($json);
echo $data->results[0]->body;

这将回显A guide to cultural...

【讨论】:

  • 这可以呼应body,但是如果有10个项目,我会写echo $data->results[0]->body;echo $data->results[1]->body;...?谢谢。
  • 是的。或者使用foreach ($data->results as $result) { echo $result->body; } 回显所有“body”。
  • 非常感谢,我收到了所有$result->body
  • 如果你想把你的 JSON 数据放到一个网页上,你可以使用客户端脚本,比如 JavaScript。例如:document.getElementById("<id-of-your-div>").innerHTML = <json-body>(如果你使用 jQuery,这会容易得多)。
【解决方案2】:

在文件内容上使用json_decode(),您可以使用file_get_contents($url) 检索它,然后您就有了一个可用于构建HTML 的数组。

$url="http://api.nytimes.com/svc/search/v1/article?format=json&query=usa&rank=newest&api-key=mykey";
$dataRaw = file_get_contents($url);

if ($dataRaw) {
  $data = json_decode($dataRaw, true);
  foreach ($data['results'] as $cEntry) {
?>
  <div class="body">
      <?php echo $cEntry['body']; ?>
  </div>
<?php
  }
}

【讨论】:

  • 谢谢@Orbling,但在 `foreach ($data['results'] as $cEntry) {`
  • @cj333:抱歉,愚蠢的 PHP 默认不会将 JSON 数组转换为实际数组。您必须将第二个参数指定为 json_decode() 的 true 才能执行此操作。编辑了代码。 php.net/manual/en/function.json-decode.php
【解决方案3】:

我不确定你为什么会这样做,但假设启用了fopen() URL 打开,你可以这样做...

echo file_get_contents($url);

【讨论】:

    【解决方案4】:

    喜欢这个?

    <?php
    
    $url="http://api.nytimes.com/svc/search/v1/article?format=json&query=usa&rank=newest&api-key=mykey";
    $json = file_get_contents($url);
    echo $json;
    

    【讨论】:

    • file_get_contents() 不是从外部 URL 获取数据的好选择,因为它无法处理超时或在代理后面运行。请改用cURL
    【解决方案5】:

    将 JSON 字符串加载到 PHP 中后,您可以使用函数 json_decode() 将其转换为 PHP 数组。然后,您可以将适当的数组元素打印到您的 HTML 输出中,就像使用任何其他 PHP 变量一样。

    【讨论】:

      【解决方案6】:

      试试这个:

      $jsonDecoded = json_decode($yourJsonEncodedData);
      echo $jsonDecoded->results->body;
      

      【讨论】:

        猜你喜欢
        • 2017-07-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-08
        • 1970-01-01
        • 2021-08-09
        • 2017-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多