How to send a GET request from PHP?

2018-12-31 22:05发布

I'm planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL.

How do I do it in PHP?

标签: php http get
7条回答
柔情千种
2楼-- · 2018-12-31 22:26

Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )

Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part

查看更多
怪性笑人.
3楼-- · 2018-12-31 22:35

http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.

$response = http_get("http://www.example.com/file.xml");
查看更多
怪性笑人.
4楼-- · 2018-12-31 22:38

I like using fsockopen open for this.

查看更多
唯独是你
5楼-- · 2018-12-31 22:40

Unless you need more than just the contents of the file, you could use file_get_contents.

$xml = file_get_contents("http://www.example.com/file.xml");

For anything more complex, I'd use cURL.

查看更多
时光乱了年华
6楼-- · 2018-12-31 22:42

In the other hand, using REST API of other servers are very popular in PHP. Suppose you are looking for a way to redirect some HTTP requests into the other server (for example getting an xml file). Here is a PHP package to help you:

https://github.com/romanpitak/PHP-REST-Client

So, getting the xml file:

$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();
查看更多
笑指拈花
7楼-- · 2018-12-31 22:44

Remember that if you are using a proxy you need to do a little trick in your php code:

(PROXY WITHOUT AUTENTICATION EXAMPLE)

<?php
$aContext = array(
    'http' => array(
        'proxy' => 'proxy:8080',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;
?>
查看更多
登录 后发表回答