duanran6441 2016-03-24 10:11
浏览 117
已采纳

PHP - 将php数组转换为JS对象时遇到麻烦

I'm new to php and having some troubles converting php array to JS object. I'm trying to get information of a given youtube video. I'm able to receive the info on the client side, but only as php array. I tried using $.parseJSON() but the data gets polluted with backspaces and redundant characters.
JS (using angular $http):

$http({
    url: "assets/controllers/youtubeInfo.php",
    method: "POST",
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    data: $.param({ getInfo: videoUrl })
}).success(function(data, status, headers, config) {
    //    console.log(JSON.parse(data));
    console.log(data);
}).error(function(data, status, headers, config) { });

PHP code:

function get_youtube($url) {
    $youtube = "http://www.youtube.com/oembed?url=".$url."&format=json";

    $curl = curl_init($youtube);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $return = curl_exec($curl);
    curl_close($curl);
    return json_decode($return, true);
}

$url = $videoKey;

// Display Data 
print_r(get_youtube($url));

This is my output:

Array
(
    [title] => StarCraft - OST
    [html] => <iframe width="459" height="344" src="https://www.youtube.com/embed/pNt0iVG2VOA?feature=oembed" frameborder="0" allowfullscreen></iframe>
    [provider_name] => YouTube
    [thumbnail_height] => 360
    [author_url] => https://www.youtube.com/user/JisengSo
    [provider_url] => https://www.youtube.com/
    [type] => video
    [height] => 344
    [thumbnail_url] => https://i.ytimg.com/vi/pNt0iVG2VOA/hqdefault.jpg
    [version] => 1.0
    [author_name] => Jiseng So
    [width] => 459
    [thumbnail_width] => 480
)
  • 写回答

2条回答 默认 最新

  • dongluyi5123 2016-03-24 10:28
    关注

    Something like the following will probably work:

    PHP code:

    function get_youtube($url) {
        $youtube = "http://www.youtube.com/oembed?url=".$url."&format=json";
    
        $curl = curl_init($youtube);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $return = curl_exec($curl);
        curl_close($curl);
        return $return; //If you're only returing it to forward it there's no point decoding it before re-encoding it.
    }
    
    $url = $videoKey;
    
    // Display Data 
    echo get_youtube($url);
    

    JavaScript:

    $http({
        url: "assets/controllers/youtubeInfo.php",
        method: "POST",
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: $.param({ getInfo: videoUrl }),
        responseType: "json", //Tells it to expect JSON in the response 
    }).success(function(data, status, headers, config) {
        console.log(data);
    }).error(function(data, status, headers, config) { });
    

    Note: as far as I know, $http uses XMLHttpRequest so https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype is applicable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?