Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get XML from Remote URL with HTTP Authentication

Tags:

php

curl

xml

I have a URL which gives an xml output. It requires a username and password which I can access through a browser using the format:

http://username:[email protected]

However when I try to access it through a php file I get a 403 forbidden:

$url = "http://username:[email protected]";


$xml = @simplexml_load_file($url);
print_r($http_response_header);

I have tried using curl and setting the user agent to a browser but this still doesn't echo the data.

EDIT:

I also tried using pear's http request 2, which also gives a 403 forbidden

like image 229
David Cahill Avatar asked Dec 17 '22 00:12

David Cahill


2 Answers

You should try something like this :

$url = "http://username:[email protected]";
$xml = file_get_contents($url);
$data = new SimpleXMLElement($xml);
like image 67
HamZa Avatar answered Jan 15 '23 11:01

HamZa


For XML with basic auth URL try this

$username = 'admin';
$password = 'mypass';
$server = 'myserver.com';

$context = stream_context_create(array(
        'http' => array(
            'header'  => "Authorization: Basic " . base64_encode("$username:$password")
        )
    )
);
$data = file_get_contents("http://$server/", false, $context);
$xml=simplexml_load_string($data);
if ($xml === false) {
    echo "Failed loading XML: ";
    foreach(libxml_get_errors() as $error) {
        echo "<br>", $error->message;
    }
} else {
    print_r($xml);
}
like image 37
Rajendra Avatar answered Jan 15 '23 11:01

Rajendra