将 curl 响应保存到 php 变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16338174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:56:29  来源:igfitidea点击:

Saving a curl response into a php variable

phpcurlamazon-ec2

提问by slick1537

I am trying to access my ec2's public hostname from inside the instance.

我正在尝试从实例内部访问我的 ec2 的公共主机名。

I would like to run this command

我想运行这个命令

curl http:// 169 254.169.254/latest/meta-data/public-hostname

inside a php script and save the response to a variable. How can I do this?

在 php 脚本中,并将响应保存到变量中。我怎样才能做到这一点?

回答by Shankar Damodaran

You can do like this

你可以这样做

<?php  
//URL of targeted site  
$url = "http://www.yahoo.com/";  
$ch = curl_init();  

// set URL and other appropriate options  
curl_setopt($ch, CURLOPT_URL, $url);  
curl_setopt($ch, CURLOPT_HEADER, 0);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  

// grab URL and pass it to the browser  

$output = curl_exec($ch);  

//echo $output;

// close curl resource, and free up system resources  
curl_close($ch);  
?>  

The $outputvariable contains the response.

$output变量包含响应。

回答by dm03514

Shankar Damodaran provided an example of how to retrieve the response from a curl request, but specifically it is the

Shankar Damodaran 提供了一个如何从 curl 请求中检索响应的示例,但具体来说是

CURLOPT_RETURNTRANSFERthat does as it says and returns the result from curl_exec

CURLOPT_RETURNTRANSFER照它说的做并返回结果 curl_exec