2015-06-03 55 views
3

我需要從網站解析一些XML數據。 XML數據是原始格式,但在我需要驗證之前(使用用戶名&密碼的基本Web服務器驗證)。PHP基本認證file_get_contents()

我想:

$homepage = file_get_contents('http://user:[email protected]:PORT/folder/file'); 

,但我得到了以下錯誤:

failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized

PHP似乎有與認證問題。任何想法如何解決這個問題?

回答

5

您將需要添加流上下文以獲取請求中的額外數據。試試類似以下未經測試的代碼。它基於file_get_contents()的PHP文檔中的一個示例:

$auth = base64_encode("username:password"); 
$context = stream_context_create(['http' => ['header' => "Authorization: Basic $auth"]]); 
$homepage = file_get_contents("http://example.com/file", false, $context);