0

Normally i'm using following code to get information from external url.

$url = 'http://something.net/json/' . $ipAdd;

if (!$content = file_get_contents($url)) {
  $error = error_get_last();
  $this->logger->addInfo("HTTP request failed. Error was: " . $error['message']);
  }

What is best way to get information from external url? i mean this is right way declare url and call file_get_contents function?

  • what's this have to do with Magento? – Marius Oct 29 '15 at 12:41
  • i want to get some json info and need to store into logs.but my senior suggested its not proper way to get info.we need to use magento framework http protocol functions. – Sivakumar K Oct 29 '15 at 12:43
1

You should create your own client which follows the \Magento\Framework\HTTP\ClientInterface. Easiest way to do this is by extending the class \Magento\Framework\HTTP\Client\Curl. In your case this could look like following:

<?php
namespace Your\ModuleName\Model;

use \Magento\Framework\HTTP\Client\Curl

class Client extends Curl
{
    /**
     * Hostname
     * @var string
     */
    protected $_host = 'something.net';

    /**
     * @param string $ip
     * @return string
     */
    public function getJsonByIp($ip)
    {
        $this->get('/json/' . $ip);
        return $this->getBody();
    }
}

The usage

<?php
namespace Your\ModuleName\Model;

class MyModel
{
    /**
     * @var Client
     */
    private $client;

    /**
     * MyModel constructor.
     * @param Client $client
     */
    public function __construct(
        Client $client
    ) {
        $this->client = $client;
    }

    /**
     * @param string $ipAdd
     * @return string
     */
    public function getInfo($ipAdd)
    {
        return $this->client->getJsonByIp($ipAdd);
    }
}

Of course you should define an own interface for your client and use DI.

0
$url = 'http://something.net/json/' . $ipAdd;

You can do it using CURL functionality of php.
 $curl = curl_init();
        // Set some options - we are passing in a useragent too here
        curl_setopt_array($curl,
                           array(
                              CURLOPT_RETURNTRANSFER => 1,
                              CURLOPT_URL => $url
                           )
                         );
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
        //$resp contains now json data

        // Close request to clear up some resources
        curl_close($curl);

        $jsonResponse = json_decode($resp,true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.