2014-09-18 2 views
-1

나는 wunderground API를 사용하여 PHP를 배우기 시작했다.PHP로 웹 서비스 요청하기

xanampp/apache로 테스트 할 때 로컬에서 작동하는 다음 코드 샘플을 가지고 있지만 실제로 웹 서버에 올려 놓았을 때 웹 서비스를 호출하는 것처럼 보입니다.

코드 :

<?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"; 


?> 
XAMPP 내 컴퓨터에서 로컬

결과 :

Current temperature in is: 

오류 보고서 : I 페이지를 호스트하기 위해 지불하는 웹 서버에

Current temperature in Cedar Rapids is: 77.4 

결과

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: 
+0

무엇이 :'echo "현재 온도". $ location. "은 :"입니다. $ temp_f. "\ n"; – Pogrindis

+1

전체 오류보고를 활성화 했습니까? 'allow_url_fopen'이 비활성화되었거나 다른 문제가있을 수 있기 때문에 json을 검색 할 수 없을 가능성이 가장 높습니다. – Wrikken

+0

@Wrikken은 오류보고를 활성화하는 방법을 잘 모릅니다. 이것은 PHP로 작업 한 첫 번째 밤입니다. 웹 서비스에 약간의 경험이 있지만 PHP가없는 경우 – user2941841

답변

0

응답 : 웹 서버는 자주 file_get_contents를 허용하지 않습니다. curl 사용 :

$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"; 
+0

이것은 대안으로, 질문에 대한 "대답"이 아닙니다. 심지어 웹 서버가 cURL을 자주 허용하지 않을 수도 있습니다. –

+0

@scrowler 그러나 이것이 내 환경에서 원하는 것을 할 수있는 유일한 방법이라면 php.ini에 대한 서버 변경없이 file_get_contents를 사용하여이를 수행 할 수있는 방법이 없습니다. – user2941841