Using CURL Functions in magento way

By

April 10, 2012Magento4 Comments

PHP CURL library is used to fetch third party contents, transfer files and post data. Magento Wraps the CURL Functions in its library with its own wrapper functions. There is no Hard and Fast Rule that we need to only use this function, but the magento core code makes use of this library.
Varien_Http_Adapter_Curl class is responsible for providing the wrapper functions.

Let’s see some code snippets to understand how it works.

<?php 
mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app()

$curl = new Varien_Http_Adapter_Curl();
$curl->setConfig(array(
       'timeout'   => 15    //Timeout in no of seconds
));
$feed_url = "http://feeds.feedburner.com/magento";
$curl->write(Zend_Http_Client::GET, $feed_url, '1.0');
$data = $curl->read();
if ($data === false) {
   return false;
}
$data = preg_split('/^r?$/m', $data, 2);
$data = trim($data[1]);
$curl->close();

try {
  $xml  = new SimpleXMLElement($data);
 //Parse the XML FEED and output the data
}
catch (Exception $e) {
   echo $e->getMessage();
}

 

The above code fetches the lastest information on magento blog in xml format. The $curl->write function accepts the method name (GET,POST), URL,HTTP version,headers,body etc. The $curl->read function will execute the curl_exec() internally.

  • Tim

    Thx for sharing.

  • http://www.facebook.com/vojInfinity Khristian Voltaire

    How can you add $_POST variables with that method?

    in PHP only you can use this:

    but how to use it the magento way?

    • http://www.facebook.com/vojInfinity Khristian Voltaire

      I just figured it out a while ago…

      anyway I’ll post the codes for anyone who passed by here:

      $curl->write(Zend_Http_Client::GET, $feed_url, '1.0', $header, $body);

      The write method has a fifth argument which is the $body; which will be the postfields.
      the $body will be the $postData for CURL

      curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

      • ramesh

        Thanks for your feedback!!