如何使用 cURL 获取 JSON 数据并解码数据?

Posted

技术标签:

【中文标题】如何使用 cURL 获取 JSON 数据并解码数据?【英文标题】:How to use cURL to get jSON data and decode the data? 【发布时间】:2013-05-18 01:08:24 【问题描述】:

所以我有一个返回 JSON 对象的链接,我需要将其解码并放入 php 中的变量中。

网址

api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1

这是它返回的对象


    "count": 1,
    "threads": 
        "38752": 
            "thread_id": 38752,
            "node_id": 4,
            "title": "The ShadyCraft Beta Launch!",
            "reply_count": 45,
            "view_count": 946,
            "user_id": 2,
            "username": "Shady",
            "post_date": 1366956695,
            "sticky": 0,
            "discussion_state": "visible",
            "discussion_open": 1,
            "discussion_type": "",
            "first_post_id": 226167,
            "first_post_likes": 7,
            "last_post_date": 1369094302,
            "last_post_id": 228226,
            "last_post_user_id": 2,
            "last_post_username": "Shady",
            "prefix_id": 19,
            "tinhte_xentag_tags": "a:4:i:0;s:9:\"minecraft\";i:2;s:4:\"news\";i:3;s:14:\"private server\";i:1;s:10:\"shadycraft\";",
            "content": 
                "count": 1,
                "content": 
                    "226167": 
                        "post_id": 226167,
                        "thread_id": 38752,
                        "user_id": 2,
                        "username": "Shady",
                        "post_date": 1366956695,
                        "message": "[ATTACH=full]4143[\/ATTACH]\n \nWe've completely restructured ShadyCraft, and today will be the launch of the ShadyCraft beta.\n \nCurrent Features\n[LIST]\n[*]Towns\n[*]Nations\n[*]All out wars\n[*]A live update map\n[*]No White-list\n[*]Earn Money\n[*]Griefing allowed where possible\n[\/LIST]\nThese are just some features which have a lot more things behind them. For instance, there is town and nation upkeep, tax, kingdoms, mayors, and kings.\n \nWe really wanted to have the server self-governed and this is why griefing and PvP are allowed where ever they are possible. All towns and nations cannot be griefed by other members. You can create a town and buy plots for it and expand the town as you wish.\n \n[SIZE=4]All of this is shown in the live updating map located [URL='http:\/\/50.7.6.116:8123']here[\/URL].[\/SIZE]\n \n[SIZE=4][SIZE=6]Join the Beta Now[\/SIZE][\/SIZE]\n[SIZE=6]Server-IP: 50.7.6.116[\/SIZE]\n \n \n[USER=118053]Frenchy[\/USER] and [USER=4863]Wolfbane[\/USER]",
                        "ip_id": 747429,
                        "message_state": "visible",
                        "attach_count": 1,
                        "position": 0,
                        "likes": 7,
                        "like_users": "a:5:i:0;a:2:s:7:\"user_id\";i:105699;s:8:\"username\";s:6:\"kvothe\";i:1;a:2:s:7:\"user_id\";i:146724;s:8:\"username\";s:12:\"Graveyard219\";i:2;a:2:s:7:\"user_id\";i:70182;s:8:\"username\";s:9:\"wmbrown18\";i:3;a:2:s:7:\"user_id\";i:5473;s:8:\"username\";s:9:\"Oblivious\";i:4;a:2:s:7:\"user_id\";i:118053;s:8:\"username\";s:7:\"Frenchy\";",
                        "warning_id": 0,
                        "warning_message": "",
                        "anonymous_posting_real_user_id": 0,
                        "anonymous_posting_real_username": ""
                    
                
            
        
    

我真的只对这个感兴趣

"title":"The ShadyCraft Beta Launch!",  
"reply_count:"45, 
"view_count": 946,  
"user_id":2, 
"username":"Shady", 
"post_date":1366956695, 
"sticky":0, 
"discussion_state":"visible",
"discussion_open":1,

最后是消息

[ATTACH=full]4143[/ATTACH]

We've completely restructured ShadyCraft, and today will be the launch of the ShadyCraft beta.

Current Features
[LIST]
[*]Towns
[*]Nations
[*]All out wars
[*]A live update map
[*]No White-list
[*]Earn Money
[*]Griefing allowed where possible
[/LIST]
These are just some features which have a lot more things behind them. For instance, there is town and nation upkeep, tax, kingdoms, mayors, and kings.

We really wanted to have the server self-governed and this is why griefing and PvP are allowed where ever they are possible. All towns and nations cannot be griefed by other members. You can create a town and buy plots for it and expand the town as you wish.

[SIZE=4]All of this is shown in the live updating map located [URL='http://50.7.6.116:8123']here[/URL].[/SIZE]

[SIZE=4][SIZE=6]Join the Beta Now[/SIZE][/SIZE]
[SIZE=6]Server-IP: 50.7.6.116[/SIZE]


[USER=118053]Frenchy[/USER] and [USER=4863]Wolfbane[/USER]

那么如何提取 JSON 对象并将其放入 PHP 中的更正变量中,以便以后使用?

变量如:$username$user_id$message$title$discussionState 等。

我只需要知道如何检索 JSON 对象,然后将数据提取到 PHP 中的变量中。

我现在能够获取 PHP 数组,但在调用正确值时遇到了一些麻烦。这是数组。

Array ( [count] => 1 [threads] => Array ( [13] => Array ( [thread_id] => 13 [node_id] => 4 [title] => 论坛整合即将完成! [reply_count] => 0 [view_count] => 0 [user_id] => 59 [username] => Faeron [post_date] => 1369257302 [sticky] => 0 [discussion_state] => 可见 [discussion_open] => 1 [discussion_type] => [first_post_id] => 23 [first_post_likes] => 0 [last_post_date] => 1369257302 [last_post_id] => 23 [last_post_user_id] => 59 [last_post_username] => Faeron [prefix_id] => 1 [content] => 数组 ([count] => 1 [content] => 数组 ( [23] => 数组 ( [post_id] => 23 [thread_id] => 13 [user_id] => 59 [用户名] => Faeron [post_date] => 1369257302 [消息] => 这是 自从我们开始将 phanime 论坛与 主站点。我们现在已经完成了与phanime的整合 论坛和主站点。你不会再注意到有两个 运行 phanime 的平台,但只有一个。我们的下一步是 为论坛设置主题,使其看起来像主站点! [ip_id] => 268 [message_state] => 可见 [attach_count] => 0 [position] => 0 [likes] => 0 [like_users] => a:0: [warning_id] => 0 [warning_message] => ) ) ) ) ) )

现在假设这个数组被命名为$array,那么要获取第一个元素的值“[count]”,我不能只说以下内容:print $array["[count]"]

如果元素本身具有值作为数组,那就是[threads] 元素。我如何获得,也许是 [thread_id] 元素的值?

【问题讨论】:

【参考方案1】:

我想这个会回答你的问题:P

$url="https://.../api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=‌​desc&limit=1&grab_content&content_limit=1";

使用cURL

//  Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
var_dump(json_decode($result, true));

使用file_get_contents

$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));

访问

$array["threads"][13/* thread id */]["title"/* thread key */]

$array["threads"][13/* thread id */]["content"/* thread key */]["content"][23/* post id */]["message" /* content key */];

【讨论】:

我已经更新了这个问题,但我在使用 JSON 返回的 PHP 数组时遇到了一点困难。如果可以,请阅读它的底部。 嗨!由于您的回答,我正在接近类似的问题,但仍然卡在atm,您介意看一下吗? ***.com/questions/28033267/… 没错。 CURLOPT_RETURNTRANSFER 给我正确的结果(y)谢谢! 花费数小时后,添加行 // 禁用 SSL 验证 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);返回结果。【参考方案2】:

要获取不需要使用 cURL 的对象(您正在将另一个 dll 加载到内存中并具有另一个依赖项,除非您真的需要 curl 我会坚持使用内置的 php 函数),您可以使用一个简单的 php file_get_contents (网址)功能: http://il1.php.net/manual/en/function.file-get-contents.php

$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");

$json_object = json_decode($unparsed_json);

然后 json_decode() 将 JSON 解析为 PHP 对象,或者如果您将 true 传递给第二个参数,则为数组。 http://php.net/manual/en/function.json-decode.php

例如:

$json = '"a":1,"b":2,"c":3,"d":4,"e":5';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array

【讨论】:

网址呢?如何首先检索 jSON 对象并将其设置为 $json 变量? url 为:/api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1 返回 JSON 对象。 我已经更新了这个问题,但我在处理由 jSON 返回的 PHP 数组时遇到了一点困难。如果可以,请阅读它的底部。 这是不正确的。您不能将 URL 传递给 file_get_contents()... 它必须是文件名(路径)。 @HenrikPetterson:file_get_contents 绝对可以用于获取 URL,而不仅仅是本地文件。尽管 cURL 提供了更多选项,并且对于除了最简单的用例之外的所有用例来说可能是更好的选择。在这里查看更多信息:php.net/manual/en/function.file-get-contents.php【参考方案3】:

你可以用它来卷曲:

function fakeip()  
  
    return long2ip( mt_rand(0, 65537) * mt_rand(0, 65535) );   
  

function getdata($url,$args=false) 
 
    global $session; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".fakeip(),"X-Client-IP: ".fakeip(),"Client-IP: ".fakeip(),"HTTP_X_FORWARDED_FOR: ".fakeip(),"X-Forwarded-For: ".fakeip())); 
    if($args) 
     
        curl_setopt($ch, CURLOPT_POST, 1); 
        curl_setopt($ch, CURLOPT_POSTFIELDS,$args); 
     
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888"); 
    $result = curl_exec ($ch); 
    curl_close ($ch); 
    return $result; 
 

然后读取 Json:

$result=getdata("https://example.com");

然后:

///Deocde Json
$data = json_decode($result,true);
///Count
             $total=count($data);
             $Str='<h1>Total : '.$total.'';
             echo $Str;
//You Can Also Make In Table:
             foreach ($data as $key => $value)
              
          echo '  <td><font  face="calibri"color="red">'.$value[type].'   </font></td><td><font  face="calibri"color="blue">'.$value[category].'   </font></td><td><font  face="calibri"color="green">'.$value[amount].'   </font></tr><tr>';

           
           echo "</tr></table>";
           

你也可以使用这个:

echo '<p>Name : '.$data['result']['name'].'</p>
      <img src="'.$data['result']['pic'].'"><br>';

希望这会有所帮助。

【讨论】:

这对我有帮助。但我不得不在我的用例的 foreach 输入中用 $data['result'] 替换 $data。【参考方案4】:

使用此功能:http://br.php.net/json_decode 这将自动创建 PHP 数组。

【讨论】:

【参考方案5】:

你也可以使用

$result = curl_exec($ch);
return response()->json(json_decode($result));

【讨论】:

【参考方案6】:

你可以用这个:

curl_setopt_array($ch, $options);
$resultado = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info["url"]);

【讨论】:

以上是关于如何使用 cURL 获取 JSON 数据并解码数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用数组对 API 数据进行 Json 解码?

php 通过curl传递的json数据如何获取

在命令行中使用 curl 通过 JSON 对象发布数据

如何在php中解码从curl产生的json文件

使用 PHP Curl 发布数据并检索响应?

用 php 提取 Instagram 信息——解码然后呢?