2016-03-25 24 views
1

Ich bin neu mit PHP. Ich versuche, Videodetails von api zu bekommen. Mein Versuch ist,Parsing googleapi Ausgabe PHP

public static function get_statistics($id=""){ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/youtube/v3/videos?part=statistics&id='.$id.'&key=<api_key>'); 
    $result = curl_exec($ch); 
    curl_close($ch); 

    $obj = json_decode($result); 
    $items = $obj->items; 
    return $items; 
    } 

Google api Ausgang

{ 
"kind": "youtube#videoListResponse", 
"etag": "\"q5k97EMVGxODeKcDgp8gnMu79wM/3rwcD8mpPjKqGuWm_i6VncLIf8Y\"", 
"pageInfo": { 
    "totalResults": 1, 
    "resultsPerPage": 1 
}, 
"items": [ 
    { 
    "kind": "youtube#video", 
    "etag": "\"q5k97EMVGxODeKcDgp8gnMu79wM/G0FH__iOsQSluyo6j8IQWdxgcCI\"", 
    "id": "TruIq5IxuiU", 
    "statistics": { 
    "viewCount": "19736248", 
    "likeCount": "119522", 
    "dislikeCount": "3710", 
    "favoriteCount": "0", 
    "commentCount": "22205" 
    } 
    } 
] 
} 

ist Wie kann ich die „Anzahl der Aufrufe“ aus der obigen Ausgabe erhalten

Antwort

0

Sie die Anzahl der Aufrufe mit einem einfachen regulären Ausdruck bekommen kann und die php preg_match Funktion (Php.net Pregmatch()):

Hier ist ein exemple:

 $string = '{ 
    "kind": "youtube#videoListResponse", 
    "etag": ""q5k97EMVGxODeKcDgp8gnMu79wM/3rwcD8mpPjKqGuWm_i6VncLIf8Y"", 
    "pageInfo": { 
     "totalResults": 1, 
     "resultsPerPage": 1 
    }, 
    "items": [ 
     { 
     "kind": "youtube#video", 
     "etag": ""q5k97EMVGxODeKcDgp8gnMu79wM/G0FH__iOsQSluyo6j8IQWdxgcCI"", 
     "id": "TruIq5IxuiU", 
     "statistics": { 
     "viewCount": "19736248", 
     "likeCount": "119522", 
     "dislikeCount": "3710", 
     "favoriteCount": "0", 
     "commentCount": "22205" 
     } 
     } 
    ] 
    }'; 
    preg_match('/viewCount": "(.*?)"/', $string, $viewCount); 
    $viewCount = $viewCount[1]; 
    echo $viewCount;