我有一个php代码,用于检索DOMDocument中的原子提要(提要未保存到文件中)
我需要开始使用基本身份验证来检索Feed。
是否可以,或者我是否必须先将Feed保存到文件中?
我的工作代码:
$doc = new DOMDocument();
$doc->load($feedurl);
$feed = $doc->getElementsByTagName("entry");
我试过这个:
$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");
但它不起作用(我得到一个空的$doc
)
任何人都知道怎么做?
答案 0 :(得分:0)
您需要使用fopen来读取Feed并直接将内容传递给DOMDocument,如下所示:
$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 );
另外,php curl比fopen好,请看:How do I make a request using HTTP basic authentication with PHP curl?