13

I am trying to make a HTTP Request from one of my controller to contact another URL, the goal being to contact another URL, and to simply print the HTML answer in my page. I tried :

$r = new Request();
$r->create('http://www.google.com', 'GET');

return $this->render(...mytemplate..., array('name' => $r->getContent());



My template is simply printing the variable "name".
Now when I do that, nothing is returned. It seems to me that the request is never sent, which is why nothing is returned.

My question is : how do I send the request and get the content of the response?

Thanks in advance.

6 Answers 6

18

EDIT: I made a GremoBuzzBundle for Buzz browser. It's similar to SensioBuzzBundle but it has some nice configuration options.

I would suggest to use Buzz browser and dependency injection. Buzz is a wrapper around cURL or file_get_contents. Edit your deps file adding these lines:

[Buzz]
    git=https://github.com/kriswallsmith/Buzz.git
    target=/buzz

Then install vendors to actually download the library:

php bin/vendors install

Then add two services (src/YourCompany/YourBundle/Resources/config/services.yml):

# cURL client for Buzz
buzz.client.curl:
  class:  Buzz\Client\Curl
  public: false
  calls:
    - [setVerifyPeer, [false]]

# Buzz browser
buzz.browser:
  class:     Buzz\Browser
  arguments: ['@buzz.client.curl']

The first service is the client (i prefer cURL over file_get_contents), the latter is the browser itself. The last step is to add one line of code in the autoloader (app/autoload.php):

$loader->registerNamespaces(array(
    'Buzz' => __DIR__.'/../vendor/buzz/lib',
));

Then you can get the service and user the browser in your controller code:

$browser = $this->get('buzz.browser');
$response = $browser->get('http://www.google.com');
7
  • 1
    What dependency am I supposed to edit? Is it the routing.yml or something else? I'm a little lost here :/ Thanks for the answer anyway, it's really helpful! May 16, 2012 at 14:43
  • @GabrielTheron first deps file, then src/Company/YourBundle/Resources/config/services.yml (for services) and the app/autoload.php.
    – gremo
    May 16, 2012 at 14:50
  • I get an error when I'm trying to load the page. It says "There is no extension able to load the configuration for "buzz.client.curl"" and "Looked for namespace "buzz.client.curl", found none". Any idea where it comes from? May 16, 2012 at 15:06
  • @GabrielTheron i'm using it right now without problems at all. You can try: 1) Check that curl is enable and loaded in you php.ini file 2) Clear Symfony2 cache 3) Ensure that vendos/buzz/lib/Buzz/Client/Curl.php
    – gremo
    May 16, 2012 at 15:20
  • Tried both :/ Nevermind, I'll sort this out. Thank you for the answers! May 16, 2012 at 15:21
18

Two problems.

First of all, that's not the proper usage of Symfony\Component\HttpFoundation\Request::create(), which is a static initializer/factory of sorts. Your code should look like this

$r = Request::create( 'http://www.google.com', 'GET' );

Now you have a proper Request object. However, this is irrelevant which is your second problem: that's not how Symfony's request object is designed to work. Its purpose is not for executing HTTP requests, its for representing them as objects in the framework.

Long story short, you can't do it that way. Perhaps you can use cURL to scrape the page you want?

1
  • 1
    Thank you for your answer. I'm trying to use cURL but Symfony isn't finding it. I'll have to sort out why now... May 16, 2012 at 14:21
9

I would recommend you using GuzzleHttp Client - best client that I know: http://docs.guzzlephp.org/en/latest/

There is already nice bundle that integrates it into Symfony2 project: https://github.com/8p/GuzzleBundle

Then from your controller you can call:

$client   = $this->get('guzzle.client');

// GET request with parameters
$response = $client->get('http://httpbin.org/get', [
    'headers' => ['X-Foo-Header' => 'value'],
    'query'   => ['foo' => 'bar']
]);
$code = $response->getStatusCode();
$body = $response->getBody();

More info can be found on: http://docs.guzzlephp.org/en/latest/index.html

1
  • That's actually a very good bundle, I've been using it to plug on a REST api, works like a charm! Mar 23, 2015 at 8:47
8

Why not use curl? From PHP manual

$ch = curl_init("http://www.example.com/");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

result = curl_exec($ch);
curl_close($ch);
2
  • 1
    I will look into it, but doesn't it require that I write into a file? May 16, 2012 at 14:11
  • No, curl's result is a string value.
    – Acyra
    Oct 9, 2012 at 16:28
3

Apparently, you can use Symfony's built-in HTTP client. See: http://api.symfony.com/2.0/Symfony/Component/HttpKernel.html

The following is a very crude codebase, using Silex (built on top of Symfony). It simply instantiates a new HTTP client.

<?php
require_once __DIR__ . '/silex/vendor/autoload.php';

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Client;
//use Symfony\Component\HttpFoundation\Response;

$dispatcher = new EventDispatcher();
$resolver = new ControllerResolver();
$kernel = new HttpKernel( $dispatcher, $resolver );

$client = new Client( $kernel );
var_dump( $client );

?>

You also have a detailed example of a HTTP client for Symfony2 as part of the unit testing documentation. See: http://symfony.com/doc/current/book/testing.html

BUT (edit) these clients are local to your app. The concepts illustrated here are better implemented with the BrowserKit component of Symfony2. A headless browser within Symfony.

Better even, use Goutte for requests to external websites. See https://github.com/FriendsOfPHP/Goutte for details.

3

https://github.com/CircleOfNice/CiRestClientBundle

Nice API for easy usage of the curl library and it returns a symfony response instead of a string result

$restClient = $this->container->get('ci.restclient');

$restClient->get('http://www.someUrl.com');
$restClient->post('http://www.someUrl.com', 'somePayload');
$restClient->put('http://www.someUrl.com', 'somePayload');
$restClient->delete('http://www.someUrl.com');
$restClient->patch('http://www.someUrl.com', 'somePayload');

$restClient->head('http://www.someUrl.com');
$restClient->options('http://www.someUrl.com', 'somePayload');
$restClient->trace('http://www.someUrl.com');
$restClient->connect('http://www.someUrl.com');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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