web-dev-qa-db-fra.com

Comment utiliser cURL pour obtenir des données jSON et décoder les données?

Donc, j'ai un lien qui retourne un objet jSON, et j'ai besoin de le décoder et de le mettre dans des variables en PHP. 

URL

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

C'est l'objet qu'il renvoie 

{
    "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": ""
                    }
                }
            }
        }
    }
}

Je ne suis vraiment intéressé que par le 

"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,

et enfin le message 

[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]

Alors, comment puis-je extraire l'objet jSON et le mettre pour corriger les variables en PHP que je pourrai utiliser par la suite? 

Des variables telles que: $username, $user_id, $message, $title, $discussionState, etc.

J'ai juste besoin de savoir comment récupérer l'objet jSON, puis extraire les données en variables en PHP.  

Je peux maintenant obtenir le tableau PHP, mais j'ai quelques problèmes pour appeler les valeurs correctes. Voici le tableau.

Array ([count] => 1 [threads] => Array ([13] => Array ([ID_fil]] => 13 [ID_noeud] => 4 [titre] => Intégration du forum presque terminée! [Numéro de réponse] => 0 [view_count] => 0 [user_id] => 59 [nom d'utilisateur] => Faeron [post_date] => 1369257302 [sticky] => 0 [discussion_state] => Visible [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_user_id] => 59 [last_post_user_id] =>. Faeron [prefix_id] => 1 [contenu] => Array ([nombre] => 1 [contenu] => Array ([23] => Array ([post_id] => 23 [ID_t fil] => 13 [ user_id] => 59 [nom d'utilisateur] => Faeron [post_date] => 1369257302 [message] => C'est Il y a longtemps que nous avons commencé à intégrer les forums Phanime avec le site principal. Nous ont maintenant terminé l'intégration avec phanime Forums et le site principal. Vous ne remarquerez plus qu'il existe deux plates-formes exécutant phanime, mais uniquement sur e. Notre prochaine étape consiste à thème les forums pour faire ressembler le site principal! [ip_id] => 268 [message_state] => visible [attach_count] => 0 [position] => 0 [likes] => 0 [like_users] => a: 0: {} [warning_id] => 0 [warning_message] =>))))))

Supposons maintenant que ce tableau s'appelle $array, puis pour obtenir la valeur "[nombre]" du premier élément, je ne peux pas simplement dire ce qui suit: print $array["[count]"] <- ceci renvoie une erreur. 

Qu'en est-il de l'élément qui a une valeur sous forme de tableau lui-même, qui est l'élément [threads]. Comment puis-je obtenir, peut-être la valeur de l'élément [thread_id]

72
Maaz

Je pense que celui-ci répondra à votre question: 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";

Utilisation de 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));

Utilisation de file_get_contents

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

Accéder à

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

Et

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

pour obtenir l'objet, vous n'avez pas besoin d'utiliser cURL (vous chargez une autre dll en mémoire et vous avez une autre dépendance, à moins que vous n'ayez vraiment besoin de curl, je vais m'en tenir aux fonctions php intégrées), vous pouvez utiliser un simple php file_get_contents (url) fonction: 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);

puis json_decode () analyse JSON dans un objet PHP ou dans un tableau si vous passez true au deuxième paramètre. http://php.net/manual/en/function.json-decode.php

Par exemple:

$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
10
Dory Zidon

Vous pouvez utiliser ceci pour Curl:

    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; 
} 

Alors pour lire Json:

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

Ensuite :

///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>";
           }

Vous pouvez également utiliser ceci:

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

J'espère que cela a aidé.

5

Utilisez cette fonction: http://br.php.net/json_decode Ceci créera automatiquement des tableaux PHP.

0

vous pouvez aussi utiliser 

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