Read Remote Content or File using Zend
Today I was looking around for sample to read a remote file in PHP or even better using Zend. Well there are quite a few good samples that demonstrate the use of native PHP functions: fopen, file_get_contents, or curl but I hardly find examples using Zend. Perhaps it’s just not my luck. But the good thing is I managed to write my own code using Zend upon reading through few samples from Zend documentation. Here goes the code.
/**
* Read the remote file and send the content as the response
*
* @author Jonathan Loe
* @date May 05 2009
*/
protected function readAndSendRemoteContent( $url )
{
// Set the configuration parameters
$config = array( 'adapter' => 'Zend_Http_Client_Adapter_Socket' );
// Instantiate a client object
$client = new Zend_Http_Client( $url, $config );
$response = $client->request();
$this->getResponse()
->setHeader( 'Content-type', $response->getHeader( 'Content-type' ) )
->appendBody( $response->getRawBody() )
->sendResponse();
}
First line of code is to set the adapter as Zend_Http_Client_Adapter_Socket. Next line is to specify the remote url along with the adapter set in the config and make the request. My last code is to send whatever was received and send it to the client as a response with the same ‘Content-type’. $this refers to the instance of the Zend controller class.
It’s that simple hey? :)
PS: If you’re looking for other samples which demonstrate use of the native functions. Here are a few links you may be interested in.
Links:
Don't leave just yet! You may also be interested to take a quick look at my other posts.
