2

How replace file_get_contents with Zend_Http_Client ?(differnce in encoding etc..)

code that should be replaced:

$url='http://google.com';$timeout=60;
$t = stream_context_create(array('http' => array('timeout' => $timeout)));
$content = @file_get_contents($url,0,$t);

My Solution:

$url='http://google.com';$timeout=60;
$client = new Zend_Http_Client($url, array('timeout' => $timeout));
$content=$client->request()->getBody();

please do you have better solution, does my solution have weak parts?


Edit:Improved solution

function getResponse($url='http://google.com',$timeout=60){
    $client = new Zend_Http_Client($url, array('timeout' => $timeout));
    if($content->isError())    {
            return null;
    }
    return $content->getBody();
 }

Remark: event better can be use of curl adapter that doing work much faster.

Thanks, Yosef

Charles
  • 50,943
  • 13
  • 104
  • 142
Ben
  • 25,389
  • 34
  • 109
  • 165

1 Answers1

1

It's ok. You can also check what the response code is and act based on that. You can get codes like 500, 404 or 403 in some cases.

Tomáš Fejfar
  • 11,129
  • 8
  • 54
  • 82
  • Which code do you suggest to add?maybe its better to check which response code succees like 200 etc.. because theoreticly exist much more failed response code? see my edit please – Ben Mar 04 '11 at 10:48
  • 1
    @Yosef: Yes, I'd reverse the check to only return the body on success status codes (ie. 2xx). – wimvds Mar 04 '11 at 12:03
  • isSuccess check only 2.. not 3.. that also could be good, soo I use isError that check 4.. + 5.. responsed status – Ben Mar 04 '11 at 13:11
  • Depends on your use case. You can set the redirections using `$config = array( 'adapter' => 'Zend_Http_Client_Adapter_Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true), );` as constructor param ;) – Tomáš Fejfar Mar 06 '11 at 00:54