【问题标题】:How to output json data in array using curl如何使用curl在数组中输出json数据
【发布时间】:2014-11-28 06:30:17
【问题描述】:

我这里有代码,可以使用 curl 获取 json 数据。现在我想回显所有数据。这将不显示任何输出。

<?php
$json = file_get_contents('myurl');
$data = json_decode($json);
print_r($data);
?>

这是来自我的 url 的 json:

 ({"Response_Code":"0000","ResultMobilePrefix":["0917","0905","0906","0915","0916","0926","0927","0937","0935","0817","0936","0922","0923",
"0932","0933","0934","0942","0943","0907","0908","0909","0910","0912","0918","0919","0920","
0921","0928","0929","0930","0938","0939","0948","0949","0925","0989","0999","0947","0998","
0946","0975","0977"]});

【问题讨论】:

    标签: php arrays json curl


    【解决方案1】:

    你只需要 echo json_encode($json);

    【讨论】:

      【解决方案2】:

      使用true将其转换为数组;

      $data = json_decode($json,true);
      echo '<pre>';
      print_r($data);
      

      【讨论】:

        【解决方案3】:

        用于以格式显示 json 使用 json_encode() 并用于正确格式使用 JSON_PRETTY_PRINT

        header('Content-type: application/json');
        echo json_encode($json,JSON_PRETTY_PRINT);
        

        【讨论】:

          【解决方案4】:

          您需要先去掉 JSON 文件中的括号和分号,然后才能使用 json_decode();

          <?php
              $json = file_get_contents('myurl');
          
              //remove the brackets
              $json = str_replace("(", "", $json);
              $json = str_replace(")", "", $json);
          
              //remove the semicolon
              $json = str_replace(";", "", $json);
          
              $data = json_decode($json);
              print_r($data);
          ?>
          

          这有点难看,但希望你明白,你需要先删除那个字符

          【讨论】:

            【解决方案5】:

            我只是想补充一下Manish 上面解释的内容。这是 PHP Docs 关于第二个参数的说法:

            When TRUE, returned objects will be converted into associative arrays.
            

            否则你只会得到一个stdclass 对象

            【讨论】:

              【解决方案6】:

              问题是 URL 没有返回有效的 Json

              你可以试试

                var_dump($data);
              

              这将返回 null,因为它不是有效的 json,请参阅 json_decode

              这会起作用

               $json = file_get_contents('myurl');
               $json = preg_replace('/[ ]{2,}|[\t\n\r\(\)\;]/', '', trim($json));
               $data = json_decode($json);
               print_r($data);
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2016-05-22
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-05-05
                • 1970-01-01
                相关资源
                最近更新 更多