0

I have a php code which retrieves a atom feed in a DOMDocument (the feed is not saved to file)

I need to start using basic authentication for retrieving the feed.

Is it possible, or do I have to save the feed to file first?

My working code:

$doc = new DOMDocument();
$doc->load($feedurl);
$feed = $doc->getElementsByTagName("entry");

I have tried this:

$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("$username:$password")
    )
));


$doc = new DOMDocument();
$doc->load($feedurl, context);
$feed = $doc->getElementsByTagName("entry");

But it does not work (I get a empty $doc)

Anyone know how to do this?

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
Tomas Jacobsen
  • 2,368
  • 6
  • 37
  • 81

1 Answers1

0

You need to use fopen to read the feed and pass the content to DOMDocument directly, like this:

$opts = array (
        'http' => array (
                'method' => "GET",
                'header' => "Authorization: Basic " . base64_encode ( "$username:$password" ) .
                         "\r\n" 
        ) 
);

$context = stream_context_create ( $opts );

//read the feed
$fp = fopen ( $feedurl, 'r', false, $context );

//here you got the content
$context = stream_get_contents ( $fp );

fclose ( $fp );

$doc = new DOMDocument ();

//load the content
$doc->loadXML ( $context );

Also, php curl is better than fopen, see this: How do I make a request using HTTP basic authentication with PHP curl?

Community
  • 1
  • 1
Andrew
  • 5,290
  • 1
  • 19
  • 22