Tuesday 26 April 2016

CURL Work in magento code using Varien_Http_Adapter_Curl with PHP and Magento example


Magento Example

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.

$clienturl = 'https://www.omnipaymentapi.com/backoffice/tools/status.php';
$jsonData = array(
               "firstdata"=>'firstdata',
               "seconddata"=>'seconddata'
               );
$http = new Varien_Http_Adapter_Curl();
$config = array('timeout' => 30,'header'=>false); # Or whatever you like!
$http->setConfig($config);
$http->write(Zend_Http_Client::POST, $clienturl, '1.1', array(), $jsonData);
$response = $http->read();
$http->close();
$xml  = new SimpleXMLElement($response);
echo '<pre>';print_r($xml);exit;

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.

 PHP Example


$ch = curl_init(); // use curl to connect
$targetURL = "https://www.omnipaymentapi.com/backoffice/tools/status.php";
$data = array(
               "firstdata"=>'firstdata',
               "seconddata"=>'seconddata'
               );
//echo 'test';exit;
curl_setopt($ch, CURLOPT_URL, $targetURL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);

No comments:

Post a Comment