문제

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?

도움이 되었습니까?

해결책

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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top