2012-05-17 47 views
3

我有一個提供xml輸出的URL。它需要用戶名和密碼,我可以通過瀏覽器使用的格式訪問:PHP通過HTTP身份驗證從遠程URL獲取XML

http://username:[email protected]

然而,當我試圖通過一個PHP文件來訪問它,我得到一個403禁止:

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


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

我已經嘗試使用curl並將用戶代理設置爲瀏覽器,但這仍然不會回顯數據。

編輯:

我使用梨的http請求2,其也給出了403禁止

回答

4

你應該嘗試這樣的事:

$url = "http://username:[email protected]"; 
$xml = file_get_contents($url); 
$data = new SimpleXMLElement($xml); 
0

格式還試圖 - http://username:[email protected] - 是一個常規的瀏覽器理解;但如果您以編程方式發出HTTP請求,則需要設置HTTP頭以進行基本身份驗證。我不認爲*使用simplexml_load_file *支持HTTP頭信息,但你可以嘗試使用,例如:

fopen("http://$username:[email protected]"); 
0

但它只加載整數。未在xml內容中加載字符串。請參閱下面的一組結果。

[2] => SimpleXMLElement Object 
      (
       [id] => 145894 
       [name] => SimpleXMLElement Object 
        (
        ) 

       [description] => SimpleXMLElement Object 
        (
        ) 

       [start_date] => SimpleXMLElement Object 
        (
        ) 

       [end_date] => SimpleXMLElement Object 
        (
        ) 

       [allow_deep_link] => 1 
       [program_id] => 6981 
       [program_name] => SimpleXMLElement Object 
        (
        ) 

       [category_name] => SimpleXMLElement Object 
        (
        ) 

       [code] => SimpleXMLElement Object 
        (
        ) 

       [tracking_url] => SimpleXMLElement Object 
        (
        ) 

      ) 
2

對於XML與基本身份驗證URL試試這個

$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); 
} 
相關問題