복붙노트

cURL을 사용하여 jSON 데이터를 얻고 데이터를 디코딩하는 방법

PHP

cURL을 사용하여 jSON 데이터를 얻고 데이터를 디코딩하는 방법

그래서 나는 jSON 객체를 반환하는 링크를 가지고 있고 그것을 PHP에서 해독하고 변수에 넣어야합니다.

URL

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]"를 얻는다 고 말할 수 있습니다. print $ array [ "[count]"] <- 오류를 반환합니다.

배열 자체로서의 값을 가지는 요소는 무엇이며, 이것은 [threads] 요소입니다. 어떻게하면 [thread_id] 요소의 값을 얻을 수 있습니까?

해결법

  1. ==============================

    1.나는 이것이 당신의 질문에 대답 할 것이라고 생각합니다 : P

    나는 이것이 당신의 질문에 대답 할 것이라고 생각합니다 : 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();
    // Disable SSL verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // 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 */];
    
  2. ==============================

    2.객체를 얻으려면 cURL (다른 dll을 메모리에로드하고 다른 종속성이 필요하지 않습니다. PHP 함수가 내장 된 상태로 말려 야 할 필요가 없다면), 간단한 PHP를 사용할 수 있습니다. file_get_contents (url) 기능: http://il1.php.net/manual/en/function.file-get-contents.php

    객체를 얻으려면 cURL (다른 dll을 메모리에로드하고 다른 종속성이 필요하지 않습니다. PHP 함수가 내장 된 상태로 말려 야 할 필요가 없다면), 간단한 PHP를 사용할 수 있습니다. file_get_contents (url) 기능: 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
    
  3. ==============================

    3.이것을 Curl에 사용할 수 있습니다 :

    이것을 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; 
    } 
    

    다음 Json 읽기 :

    $result=getdata("https://site.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>';
    

    희망이 도움이되었습니다.

  4. ==============================

    4.이 함수를 사용하십시오 : http://br.php.net/json_decode 그러면 자동으로 PHP 배열이 만들어집니다.

    이 함수를 사용하십시오 : http://br.php.net/json_decode 그러면 자동으로 PHP 배열이 만들어집니다.

  5. ==============================

    5.이것을 사용할 수 있습니다 :

    이것을 사용할 수 있습니다 :

    curl_setopt_array($ch, $options);
    $resultado = curl_exec($ch);
    $info = curl_getinfo($ch);
    print_r($info["url"]);
    
  6. from https://stackoverflow.com/questions/16700960/how-to-use-curl-to-get-json-data-and-decode-the-data by cc-by-sa and MIT license