向PHP中的另一个PHP文件发出GET请求

问题描述:

我创建了一个名为"brain.php"的php文件,该文件带有一个"message"的get参数-例如"brain.php?msg = hello".它将以可以由应用程序处理的JSON数组进行响应.

I have created a php file called "brain.php" that takes a get parameter of "message" - so for example "brain.php?msg=hello". It will respond with a JSON array that can be handled by the application.

我已经构建了一个可以发出这些请求的JQuery应用程序,现在我正在尝试用PHP进行操作,但是我不确定如何执行.

I have built a JQuery app that can make these requests, and now I'm attempting to do it in PHP but I'm not sure how.

以下代码不起作用,因为它认为该参数是文件名的一部分

The following code does not work as it thinks the parameter is part of the filename

$response = file_get_contents("../brain.php?msg=hello");
echo $response;

以下代码可以正常工作,但只响应整个代码而不是响应

The following code kind of works but simply responds with the entirety of the code instead of the response

$response = file_get_contents("../brain.php");
echo $response;

使用?msg变量发出请求并将JSON响应存储在变量中以进行处理的最佳方法是什么?

What is the best way to make the request with the ?msg variable and store the JSON response in a variable for handling?

谢谢!

您可以使用 file_get_contents 从URL获取内容:

You can get content from URL using file_get_contents:

$response  = file_get_contents('https://httpbin.org/ip?test=test');
$jsonData = json_decode($response, true));

但是,您需要检查php.ini中是否启用了 allow_url_fopen .另外,您也可以使用 curl :

However you need to check if allow_url_fopen is enabled in your php.ini. Alternatively you can do the same with curl:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://httpbin.org/ip?test=test');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$jsonData = json_decode(curl_exec($curl), true);

curl_close($curl);