Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - How to perform an external Request

Tags:

http

php

symfony

Using Symfony2, I need to access an external API based on HTTPS.

How can I call an external URI and manage the response to "play" with it. For example, to render a success or a failure message?

I am thinking in something like (note that performRequest is a completely invented method):

$response = $this -> performRequest("www.someapi.com?param1=A&param2=B");  if ($response -> getError() == 0){     // Do something good }else{     // Do something too bad } 

I have been reading about Buzz and other clients. But I guess that Symfony2 should be able to do it by its own.

like image 215
ElPiter Avatar asked Oct 25 '12 15:10

ElPiter


1 Answers

I'd suggest using CURL:

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'www.someapi.com?param1=A&param2=B'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); // Assuming you're requesting JSON curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  $response = curl_exec($ch);  // If using JSON... $data = json_decode($response); 

Note: The php on your web server must have the php5-curl library installed.

Assuming the API request is returning JSON data, this page may be useful.

This doesn't use any code that is specific to Symfony2. There may well be a bundle that can simplify this process for you, but if there is I don't know about it.

like image 161
RobMasters Avatar answered Sep 22 '22 16:09

RobMasters