【问题标题】:How to parse this JSON url with Authorization to HTML table/ list with php如何使用 php 将这个 JSON url 解析为 HTML 表/列表的授权
【发布时间】:2021-11-07 13:09:47
【问题描述】:

我正在尝试从这里获取此 JSON 数据:https://gw.bilinfo.net/listingapi/api/export

他们在这里有一个“如何工作表”:https://developer.bilinfo.net/content/Bilinfo_XML_API.pdf

我可以通过 Authorization 连接并获取原始 JSON,但我无法使用数据制作表格。

这是我目前的代码:

    <?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';

// provide your username and password here
$auth = base64_encode("demo:ocfB6XzF73");

// create HTTP context with basic auth
$context = stream_context_create([
    'http' => ['header' => "Authorization: Basic $auth"]
]);

// query for data
$data = file_get_contents($url, false, $context);
$escaped = json_encode($data);

/*Initializing temp variable to design table dynamically*/
$temp = "<table>";

/*Defining table Column headers depending upon JSON records*/
$temp .= "<tr><th>Bilmodel</th>";
$temp .= "<th>Motor</th>";
$temp .= "<th>Drivmiddel</th></tr>";

/*Dynamically generating rows & columns*/
for ($i = 0; $i < sizeof($escaped["Vehicles"]); $i++) {
    $temp .= "<tr>";
    $temp .= "<td>" . $escaped["Vehicles"][$i]["Model"] . "</td>";
    $temp .= "<td>" . $escaped["Vehicles"][$i]["Motor"] . "</td>";
    $temp .= "<td>" . $escaped["Vehicles"][$i]["Propellant"] . "</td>";
    $temp .= "</tr>";
}

/*End tag of table*/
$temp .= "</table>";

/*Printing temp variable which holds table*/
echo $temp;
?>

【问题讨论】:

  • 如何访问带有图片的底层数组等等。如何联系他们?
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: php html json xml


【解决方案1】:

解决方案 1。 JSON_FORCE_OBJECT 对 PHP 数组值进行编码,那么即使输入数组没有任何索引,每个数组元素也会被添加到索引中。

所以你可以使用

$escaped = json_encode($data, JSON_FORCE_OBJECT);

您的代码将打印表格。

解决方案 2。 目前json_encode 将数据转换为 StdObject,您可以在其中使用箭头符号读取数据。因此,在表格中打印数据只需使用 foreach 函数读取带箭头符号的 Vehicles 对象。

 /*Dynamically generating rows & columns*/
    foreach ($escaped->Vehicles as $vehicle){
        $temp .= "<tr>";
        $temp .= "<td>" . $vehicle->Model . "</td>";
        $temp .= "<td>" . $vehicle->Motor . "</td>";
        $temp .= "<td>" . $vehicle->Propellant . "</td>";
        $temp .= "</tr>";
    }

【讨论】:

  • 哇,这太疯狂了 - 它就像一个魅力 c,) - 非常感谢!
  • @MartinWichmand 你只需要删除 for 循环然后添加上面的 foreach。另外,请确保像以前一样在没有 JSON_FORCE_OBJECT 的情况下执行 json_encode。像这样 json_encode(data);然后foreach
  • 感谢它的正常工作......非常感谢!
猜你喜欢
  • 2014-11-30
  • 2016-05-10
  • 2013-11-15
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
相关资源
最近更新 更多