如何获得结果(JSON PHP)

时间:2019-07-01 21:38:15

标签: php json

我有问题。如何获得结果?

这是我的代码:

error_reporting(E_ALL);
ini_set(log_errors, '1');  //This directive is executed 

我的JSON是:

<?php 
$api_e = file_get_contents('https://omnihost.tech/dashboard/hosts/'.$slug.'/api_ftp');
$api = json_decode($api_e); ?>
<?php foreach($api as $file){ ?>
    <tr>
        <td>#</td>
        <td><?= $file; ?></td>
        <td>--</td>
    </tr>
<?php } ?>

错误:http://prntscr.com/o98xau

2 个答案:

答案 0 :(得分:0)

json_decode可以接收两个参数,第一个参数为json,第二个参数为布尔值,该值指示(如果为true)对象将被解码为数组。您可以尝试在函数中应用第二个参数,以能够正确地使用已经完成的foreach进行迭代。

json_decode($api_e, true);

假设变量$ api_e中存储的内容是这样的:

$api_e = '{
    "data": [
        ".",
        "..",
        ".editorconfig",
        ".gitignore",
        ".htaccess",
        ".well-known",
        "README.md",
        "application",
        "assets",
        "cgi-bin",
        "composer.json",
        "contributing.md",
        "index.php",
        "license.txt",
        "readme.rst",
        "system"]
    }';

这项杰出的工作:

<?php
$api = json_decode($api_e, true);
?>
<?php foreach($api["data"] as $file){ ?>
    <tr>
        <td>#</td>
        <td><?= $file; ?></td>
        <td>--</td>
    </tr>
<?php } ?>

如果它不起作用,则您的网址可能有误,或者没有通过file_get_contents()获得正确的值,则应进行检查。

答案 1 :(得分:0)

您需要指定需要打印的列,您可以在下面尝试打印文件名

<td><?= $file['12']; ?></td>

否则,您将循环使用2个循环来打印数组中的所有数据

<?php foreach($api as $file) { ?>
    <?php foreach($file as $i => $item) { ?>
        <tr>
            <td><?= $i; ?></td>
            <td><?= $item; ?></td>
            <td>--</td>
        </tr>
    <?php } ?>
<?php } ?>