phpsymfonyhttpresponsebuzz

symfony2 Get exact content from BuzzBundle response


How can I get exact content from BuzzBundle without header or other information

currently I am using ,

 $buzz = $this->container->get('buzz');
 $response = $buzz->get('http://api.ipify.org?format=json');
 echo $response;

and output is,

HTTP/1.1 200 OK Server: Cowboy Connection: close Access-Control-Allow-Origin: * Content-Type: text/plain Date: Thu, 13 Nov 2014 14:51:40 GMT Content-Length: 14 Via: 1.1 vegur {"ip":"54.254.210.209"} 

here only {"ip":"111.20.67.90"} is desired response.

or any other way to do so, with different bundle, or i have to use curl directly in PHP code ?


Solution

  • For posterity, BuzzBundle is just a small configuration file that injects the Buzz library into Symfony.

    When you use the get() method of Browser, it returns an instance of call() with a return value of MessageInterface... so let's examine that file:

    /**
     * Returns the message document.
     *
     * @return string The message
     */
    public function __toString();
    

    This is just the equivalent of a header file if you're familiar with C++, but it's clear that the __toString() file returns the full message, including headers. So if we look through the rest of that file, we find that there's another function that gets what you want:

    /**
     * Returns the content of the message.
     *
     * @return string The message content
     */
    public function getContent();
    

    So if you treat the MessageInterface as an object instead of trying to access it like a string (which gives you its default of __toString()), this is the code you would use:

    $buzz = $this->container->get('buzz');
    $response = $buzz->get('http://api.ipify.org?format=json');
    echo $response->getContent(); // output: {"ip":"54.254.210.209"}