我是php的新手,并且遇到了将php array
转换为JS object
的麻烦。我试图获取给定YouTube视频的信息。我能够在客户端收到信息,但仅限php array
。我尝试使用$.parseJSON()
,但数据受到退格和冗余字符的污染
JS(使用角度$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代码:
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));
这是我的输出:
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
)
答案 0 :(得分:2)
要获取JS对象,请不要json_decode
输出(或再次编码):
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; // change here
}
$url = $videoKey;
// Display Data
echo get_youtube($url); // change here
答案 1 :(得分:1)
以下内容可能会起作用:
PHP代码:
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) { });
注意:据我所知,$ http使用XMLHttpRequest,因此https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype适用。