如何使用curl在数组中输出json数据

I have code here that will get json data using curl. Now I want to echo all data. This will show no output.

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

This is json coming from my url:

 ({"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"]});

6个回答



你需要的只是
echo json_encode($ json); </ p>
</ div>

展开原文

原文

All you need is echo json_encode($json);

Use true to convert it into array;

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



用于以格式显示json使用 json_encode()</ code>并使用正确的格式 JSON_PRETTY_PRINT </ code > </ p>

  header('Content-type:application / json'); 
echo json_encode($ json,JSON_PRETTY_PRINT);
</ code> </ pre>
</ DIV>

展开原文

原文

for displaying json in format use json_encode() and for proper format use JSON_PRETTY_PRINT

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

you need to get rid of the bracket and semicolon on the JSON file first before you can use the 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);
?>

this is a bit ugly, but hope you get the idea, you need to remove that character first



我只想添加 Manish 已在上面解释过。 这就是PHP Docs关于第二个参数的说法:</ p>

 当为TRUE时,返回的对象将被转换为关联数组。
</ code> </ pre>
\ n

否则你只需要一个 stdclass </ code>对象</ p>
</ div>

展开原文

原文

I just want to add to what Manish has explained above. This is what PHP Docs say about the second parameter:

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

else you will simply get a stdclass object



问题是URL没有返回有效的Json </ p>

你可以简单地尝试</ p>

  var_dump($ data); 
</ code> </ pre>

这将返回 null </ strong>,因为它不是 有效的json见 json_decode </ p>

这将起作用</ p>

  $ json = file_get_contents('myurl'); 
$ json = preg_replace('/ [] {2,} | [\ t

\(\)\;] /','',trim($ json));
$ data = json_decode($ json);
print_r($ data);
</ code> </ pre> \ n </ div>

展开原文

原文

The problem is the URL does not return a valid Json

you could simply try

  var_dump($data);

this will return null because it's not a valid json see json_decode

this will work

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问