簡體   English   中英

PHP獲取從URL加載的DOMDocument的內容類型標頭

[英]PHP get the content type header of DOMDocument loaded from url

我正在使用PHP的DOMDocument功能從遠程源檢索XML文檔(在本例中為RSS feed)。 它將XML作為DOM對象返回,我可以訪問XML標簽的內容,如下所示:

$url     =  $_POST['url']; // eg. http://example.com/page.xml
$xmlDoc  =  new DOMDocument();
$xmlDoc  -> load($url);
$channel =  $xmlDoc -> getElementsByTagName('channel') -> item(0);

這對我來說很好用,但是我想知道是否有一種方法可以檢查提供文檔的服務器是否正在發送正確的content-type標頭,在這種情況下,標頭應該是text/xmlapplication/xml 如何確定要發送的內容類型標頭?

我猜我想做的事情離確定文檔是否為有效XML更近了一步。 我知道查看內容類型標頭不能保證這一點,但是如果發送錯誤的標頭,我可能會排除一些錯誤。

這是PHP進行某些自動行為的領域之一,如果沒有多年的經驗,很難發現這些行為。 在URL上調用DOMDocument::load()調用PHP的http / https流包裝器來加載URL。 這樣做會填充一個名為$http_response_header特殊變量,變量表示緊接在前一個http / https流調用之前的標頭數組。

因此,在$xmlDoc->load($url) ,嘗試檢查$http_response_header 請注意,它不是一個易於解析的關聯數組。 相反,您需要找到Content-Type:字符串並將其在冒號:上分割。

$xmlDoc = new DOMDocument();
$xmlDoc->load($url);

// Loop over the array and look for the desired header
foreach ($http_response_header as $header) {
  // Find the header with a case-insensitive search
  // for Content-Type: 
  if (stripos($header, 'Content-Type:') === 0) {
    // and split it on : to take the second value
    // Example: "Content-Type: application/xml; charset=UTF-8"
    $content_type = trim(explode(':', $header)[1]);
  }
  // You can break out of the loop after finding it
  break;
}

注意事項-如果您接受來自$_POST格式的URL,則可能希望對可接受的值設置一些限制。 您可能會通過檢索任意URL暴露出一些安全問題(引起拒絕服務攻擊,也可能是代理濫用)

// Careful not to accept just any url anyone sends...
$url = $_POST['url'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM