Tag Archives: cURL

Magento 2 cURL

Following code get content from an external site using cURL.

<?php
 namespace PHPCodez\Layout\Block;
 
 class Footer extends \Magento\Framework\View\Element\Template {
 
 protected $_httpClientFactory;
 
 public function __construct(\Magento\Framework\View\Element\Template\Context $context,
 \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory) {
 $this->_httpClientFactory = $httpClientFactory;
 parent::__construct($context);
 }

public function getFooterContent() {
 $url = "http://127.0.0.1:81/content/footer.php";
 $client = $this->_httpClientFactory->create();
 $client->setUri($url);
 return $response = $client->request(\Zend_Http_Client::POST)->getBody(); 
 }
 }

For more option you can check vendor\magento\framework\HTTP\Client\Curl.php

addHeader()
setCredentials()
addCookie()
get() // for get request
makeRequest() // for make request
setOption() // set curl options
Share

what is cURL in php

cURL is a library that allows PHP applications to communicate with other servers. 

Example :

<?php
$url = “www.example.com”; // Desired URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$returned = curl_exec($ch);
curl_close ($ch);
echo $returned;
?>

Share

Script to read RSS feed – PHP

<?php
 $connect = curl_init("http://www.unixsite.com/feed/rss/");
 curl_setopt($connect, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($connect, CURLOPT_HEADER, 0) ;
 $result = curl_exec($connect);
 curl_close($connect);
 $data = new SimpleXmlElement($result, LIBXML_NOCDATA);
 for($i=0;$i<10;++$i) {
  if(empty($data->channel->item[$i]->title)) break;
  echo  $data->channel->item[$i]->title;
  echo  $data->channel->item[$i]->description;
 }
?>
Share