【问题标题】:Calling JSON from a php file to a HTML page从 php 文件调用 JSON 到 HTML 页面
【发布时间】:2015-06-26 09:02:43
【问题描述】:

我正在制作一个需要显示视频的 html 页面。视频的 URL 可在 jsondecode 输出中找到。这里有什么方法可以从 JSON 输出中挑选片段并在我的 html 页面中使用它吗?我已经尝试过 POST 和 GET 以及 echo,但它似乎不起作用。

明确一点:我正在尝试将其从 php 文件转换为单独的 HTML 文件。

JSON 响应位于函数的单独文件中。

public function getURL(){
    $server_url= ilObjPresentations2GoGUI::getServerUrl();
     $secret_key= ilObjPresentations2GoGUI::getSecretKey();
     $authorized_group= ilObjPresentations2GoGUI::getAuthorizedGroup();
     $link_usable= ilObjPresentations2GoGUI::getLinkUsable();
     $query = 'technology';

    $date = new DateTime('NOW');
    $ts = $date->format('Y-m-d\TH:i:s');
    $interval = 'PT' . $this->link_usable . 'H';
    $date->add(new DateInterval('PT' . $link_usable . 'H'));
    $expired = $date->format('Y-m-d\TH:i:s');
    $url = $server_url . '?action=search&query='. $query . '&group='. $authorized_group . '&ts=' . $ts . '&expired=' .$expired; 

    $token = ilObjPresentations2GoAPI::create($url,$secret_key);
    $goodurl = $url . '&token=' . $token;

    $json = file_get_contents($goodurl);
    $the_data = json_decode($json, true);}

输出:

array(9) { ["schemaVersion"]=> string(3) "1.0" ["catalogueVersion"]=> string(14) "4.0.5651.20898" ["encoding"]=> string(5) "UTF-8" ["action"]=> string(6) "search" ["query"]=> string(10) "technology" ["page"]=> string(1) "1" ["pageCount"]=> string(1) "1" ["success"]=> string(4) "true" ["response"]=> array(3) { [0]=> array(10) { ["id"]=> string(6) "bWKUL2" ["title"]=> string(57) "Technology-Based Professional Learning and Support Models" ["date"]=> string(19) "2011-12-05T10:19:21" ["contributors"]=> string(0) "" ["thumbnailUrl"]=> string(409) "https://DEMO-FORMS.presentations2go.eu/P2G/plugins/mediaservice.aspx?

(这还不是全部,否则它会是半页)

【问题讨论】:

  • var_dump($the_data);json_decode 之后的输出是什么?
  • @unixarmy 我用该数据编辑了问题。
  • 您可以使用 $the_data 从该 json 数据中获取值。以$the_data['title'] 为例。
  • @redelschaap 你如何在 HTML 中使用它?如何在这两者之间建立联系?
  • 我已将其发布为答案

标签: php html json


【解决方案1】:

您可以在 html 中使用 JSON 解码数组中的数据,只要这些文件具有 .php 扩展名或它们被 PHP 包含:

<div><?php echo $the_data['title']; ?></div>

由于您的 $the_data 数组在方法 getURL() 内,您可以返回 $the_data 数组内的 URL:

public function getURL() {
    ...

    $the_data = json_decode($json, true);

    return !empty($the_data['url']) ? $the_data['url'] : '';
}

...

<div><?php echo $your_object->getURL(); ?></div>

【讨论】:

  • 如果我需要为多个视频执行此操作怎么办?
  • 这取决于您如何获取多个视频的网址。它们都在一个 JSON 对象中吗?还是在多个对象中?
猜你喜欢
  • 2015-01-09
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多