使用file_get_contents获取json数据

时间:2016-01-14 19:36:29

标签: php json file-get-contents

我需要从此网址中检索信息:

http://example.com/ajax.php?sport=soccer&language_id=vn&block_id=page_home_1_block_home_matches_1&block_name=block_home_matches&callback_params={"date": "2016-01-14", "display": "all"}&action=updateContent&params={}

我的网址是这样的:

http://example.net/ajax.php?sport=soccer&language_id=vn&block_id=page_home_1_block_home_matches_1&block_name=block_home_matches&callback_params=%7B%22date%22%3A%20%222016-01-14%22%2C%20%22display%22%3A%20%22all%22%7D&action=updateContent&params=%7B%7D

这是ajax.php:

<?php

$sport = $_GET["sport"];
$language_id = $_GET["language_id"];
$block_id = $_GET["block_id"];
$block_name = $_GET["block_name"];
$callback_params = $_GET["callback_params"];
$action = $_GET["action"];
$params = $_GET["params"];

$url = "http://example.com/ajax.php?sport=$sport&language_id=$language_id&block_id=$block_id&block_name=$block_name&callback_params=$callback_params&action=$action&amp;params=$params";

echo file_get_contents($url);

?>

但是没有回报,这里有什么不对吗?

1 个答案:

答案 0 :(得分:1)

为安全起见,服务器可能会将allow_url_fopen设置为关闭(请参阅http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

尝试使用curl来获取数据

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
echo $data;

另外,为避免您在网址中传递的数据可能出现问题,请务必在每个变量上调用urlencode,以防其中包含&=等特殊字符。例如:

$sport = urlencode($_GET["sport"]);