【问题标题】:This Convert JSON in Array return is null此 Convert JSON in Array 返回为 null
【发布时间】:2020-04-22 05:50:12
【问题描述】:

我需要在 Array 中转换返回 JSON 来操作数据,但是当尝试将此数组设置为 null 时,我需要使用 htmlentities 为什么导航器中的返回被 json 中的 html 标签搞砸了。

这是我的代码:

<?php
try {
    function listTasks() {  

        $ch = curl_init();
        $token = 'token';
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://collab.cadastra.com.br/api/v1/projects/idproject/tasks/',

            CURLOPT_HTTPHEADER => [
                'X-Angie-AuthApiToken: ' . $token,
                'Content-Type: application/json',
                'x-li-format: json'
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_PROTOCOLS => CURLPROTO_HTTPS
        ]);

        $result = curl_exec($ch);
        $convert = htmlentities($result, ENT_QUOTES, "UTF-8"); // I did this because the return had html tags that gave problems with browser display.
        $tasks = json_decode($convert, true); //this is where I convert to array.
        // for ($i = 0; $i < count($tasks); $i++) {
        // if ($tasks[$i]["task_list_id"] == 55979) {
        //           $tasks_name[$i] = $tasks[$i]["name"];
        //       }
        //   }

        var_dump($tasks); // here it returns null, if I put print_r returns nothing.
        curl_close($ch);
        // return $result;
    }

    listTasks();
} catch (Error $e) {
    print_r($e->getMessage());
}
// print_r($_POST['email']));

有人可以帮助我吗?

【问题讨论】:

  • var_dump($result); 提供了什么?
  • 我想你的意思是 var_dump 应该带来什么?它应该带来一个数组转换任务的 json,但它是空的。
  • 我的意思是curl_exec()的返回值,这样我们就可以看到API返回的实际值是多少。
  • 我想我明白了,浏览器解释 json,但是 $convert 的 var_dump 是一个字符串,所以当我尝试数组时它返回我 null。
  • 不,不过,我所说的没有意义,因为它将是一个字符串,对不起

标签: php json api


【解决方案1】:

如果 cURL 请求以 JSON 格式响应,则应首先使用

对其进行解码
json_decode

然后只使用

htmlentities

用于指定数组索引以清除文本。然后你用你的方式,你使json字符串无效,所以它不能解码它。无论如何,您不应该使用混合 json 和 html 将其显示到浏览器中。

【讨论】:

  • 嗨,我试试,但是 htmlentities 需要一个字符串,如果我使用 json_decode 他们会在数组中转换 var ...
  • 尝试数组 map = $convert = array_map("htmlspecialchars", $tasks);但不是不行。
猜你喜欢
  • 2022-12-02
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2017-02-27
相关资源
最近更新 更多