Get youtube channel data in array

i am trying to get Youtube channel data with that api

https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&id={ Channel Id }&key={ API }

I used that code to fetch the data

    if( $_SERVER[ 'REQUEST_METHOD' ] == 'GET' && !empty( $_GET ) ){

    $channel_id = $_GET[ 'channel_id' ];

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&id=". $channel_id ."&key=AIzaSyCKAnI41bI4UGDJgYUcwrhrIfnjoD3uirM",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_POSTFIELDS => "",
      CURLOPT_HTTPHEADER => array(
        "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
        echo $response;
    }

}

?>
<form id="channelIdForm" action="<?php $_SERVER['PHP_SELF']; ?>" method="get">

    <input type="text" placeholder="Type channel id" name="channel_id" id="channelId" />
    <button type="submit">Get data</button>

</form>

And it appeared like that

{ "kind": "youtube#channelListResponse", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/pss5QFB6saoevVwzX-8y6f1U75E\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#channel", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/gPFze0Hh7eRu9O5tXiTBVyvCwa8\"", "id": "UC4QYTjhWMxiC6UwvKLVkDDA", "snippet": { "title": "حفيد برايز حفيد برايز", "description": "", "publishedAt": "2018-04-01T17:18:31.000Z", "thumbnails": { "default": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s88-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 88, "height": 88 }, "medium": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s240-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 240, "height": 240 }, "high": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s800-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 800, "height": 800 } }, "localized": { "title": "حفيد برايز حفيد برايز", "description": "" } }, "contentDetails": { "relatedPlaylists": { "uploads": "UU4QYTjhWMxiC6UwvKLVkDDA", "watchHistory": "HL", "watchLater": "WL" } }, "statistics": { "viewCount": "830460", "commentCount": "0", "subscriberCount": "3741", "hiddenSubscriberCount": false, "videoCount": "19" } } ] } 

Then i tried to convert that json to an array to pick what i want from it with index

So i tried that instead of $response

$json = $response;                                 
  $arr = json_decode($json, true);              
  $row = array_reduce($arr['items'], function($c, $v){
      $c[ key($v) ] = current($v);
      return $c;
  }, array());

  print_r( $row );

I expected to see all the indexes below item but the result was

Array ( [kind] => youtube#channel ) 

It show just kind i don't know what the problem with so if any one can help i will be appreciated!!

2 answers

  • answered 2018-07-11 03:49 Nadav

    The array_reduce function reduces an array to a single value. But it appears you are interested in multiple key/value pairs. Since json_decode($json, true); already provides you with an associated array you can retrieve specific keys via their names. Example:

    $arr = json_decode($response, true);
    $newArray = [];
    $requiredKeys = ['kind','etag'];
    foreach ($requiredKeys as $key){
          $newArray[$key] = $arr[$key];
    }
    

  • answered 2018-07-11 04:11 ivanivan

    It is a very-multi-dimensional array.

    Here's some code that prints the contents of an array. If the value it is going to print is an array, it calls itself again. You'll see it puts out Printing $json_arr[items[0][statistics] : followed by a bunch of key->value pairs, so you can find the state you want and you'll know what the parent array(s) are.

    <?php
    
    $json='{ "kind": "youtube#channelListResponse", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/pss5QFB6saoevVwzX-8y6f1U75E\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#channel", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/gPFze0Hh7eRu9O5tXiTBVyvCwa8\"", "id": "UC4QYTjhWMxiC6UwvKLVkDDA", "snippet": { "title": "حفيد برايز حفيد برايز", "description": "", "publishedAt": "2018-04-01T17:18:31.000Z", "thumbnails": { "default": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s88-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 88, "height": 88 }, "medium": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s240-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 240, "height": 240 }, "high": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s800-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 800, "height": 800 } }, "localized": { "title": "حفيد برايز حفيد برايز", "description": "" } }, "contentDetails": { "relatedPlaylists": { "uploads": "UU4QYTjhWMxiC6UwvKLVkDDA", "watchHistory": "HL", "watchLater": "WL" } }, "statistics": { "viewCount": "830460", "commentCount": "0", "subscriberCount": "3741", "hiddenSubscriberCount": false, "videoCount": "19" } } ] } ';
    
    $json_arr=json_decode($json,true);
    
    function print_array($prefix,$arr){
        print("printing ".$prefix." :\n");
        foreach($arr as $k=>$v){
            if(is_array($v)){
                print_array($prefix."[".$k."]",$v);
            }else{
                print("key: ".$k."   value:".$v." \n");
            }
        }
        return;
    }
    
    print_array("\$json_arr",$json_arr);
    
    ?>