Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

php - Symfony2 - How to perform an external Request

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...