PHP中的Web服务请求


Web Service request in PHP

我开始学习PHP,通过摆弄神童API。

我有下面的代码示例,当使用xaampp/apache进行测试时,它可以在本地工作,但当我把它放在互联网上的实际web服务器上时,它似乎并没有调用web服务。

代码:

<?php
  $json_string = file_get_contents("http://api.wunderground.com/api/key/geolookup/conditions/q/IA/Cedar_Rapids.json");
  $parsed_json = json_decode($json_string);
  $location = $parsed_json->{'location'}->{'city'};
  $temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
  echo "Current temperature in ${location} is: ${temp_f}'n";

?>

结果在我的机器上本地与示例:

Current temperature in Cedar Rapids is: 77.4

我付费托管页面的Web服务器上的结果:

Current temperature in is:

错误报告:

Warning: file_get_contents(): http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /hermes/bosnaweb01b/b2414/ipg.domainID/testt.php on line 5 Warning: file_get_contents(http://api.wunderground.com/api/key/geolookup/conditions/q/IA/Cedar_Rapids.json): failed to open stream: no suitable wrapper could be found in /hermes/bosnaweb01b/b2414/ipg.domainID/testt.php on line 5 Notice: Trying to get property of non-object in /hermes/bosnaweb01b/b2414/ipg.domainID/testt.php on line 7 Notice: Trying to get property of non-object in /hermes/bosnaweb01b/b2414/ipg.domainID/testt.php on line 7 Notice: Trying to get property of non-object in /hermes/bosnaweb01b/b2414/ipg.domainID/testt.php on line 8 Notice: Trying to get property of non-object in /hermes/bosnaweb01b/b2414/ipg.domainID/testt.php on line 8 Current temperatdure in is:

答案:Web服务器通常不允许使用file_get_contents。使用卷曲:

$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => "http://api.wunderground.com/api/key/geolookup/conditions/q/IA/Cedar_Rapids.json",
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$json_string = $resp;
$parsed_json = json_decode($json_string);
  $location = $parsed_json->{'location'}->{'city'};
  $temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
  echo "Current temperatdure in ${location} is: ${temp_f}'n";