PHP获取从url加载的DOMDocument的内容类型头

PHP获取从url加载的DOMDocument的内容类型头,php,html,xml,header,content-type,Php,Html,Xml,Header,Content Type,我正在使用PHP的DOMDocument特性从远程源检索XML文档(在本例中是RSS提要)。它将XML作为DOM对象返回,我可以访问XML标记的内容,如下所示: $url = $_POST['url']; // eg. http://example.com/page.xml $xmlDoc = new DOMDocument(); $xmlDoc -> load($url); $channel = $xmlDoc -> getElementsByTagName('c

我正在使用PHP的DOMDocument特性从远程源检索XML文档(在本例中是RSS提要)。它将XML作为DOM对象返回,我可以访问XML标记的内容,如下所示:

$url     =  $_POST['url']; // eg. http://example.com/page.xml
$xmlDoc  =  new DOMDocument();
$xmlDoc  -> load($url);
$channel =  $xmlDoc -> getElementsByTagName('channel') -> item(0);
这对我来说很好,但我想知道是否有办法检查提供文档的服务器是否发送了正确的
内容类型
标题,在本例中,标题应该是
text/xml
application/xml
。如何确定要发送的内容类型标头


我想我要做的是进一步确定文档是否是有效的XML。我知道查看内容类型标题并不能保证这一点,但如果发送了错误的标题,我可能会排除一些错误。

这是PHP执行某些自动逻辑行为的领域之一,如果没有多年的挖掘经验,很难发现这些行为。在URL上调用
DOMDocument::load()
,将调用PHP的http/https流包装器来加载URL。这样做将填充表示来自前面http/https流调用的头数组的

因此,在
$xmlDoc->load($url)
之后,尝试检查
$http\u response\u头
。请注意,它不是一个容易解析的关联数组。相反,您需要找到
内容类型:
字符串并在冒号上拆分它

$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;
}
注意事项-如果您接受来自表单
$\u POST
的URL,您可能希望对可接受的值设置一些限制。通过检索任意URL,您可能会遇到一些安全问题(会想到拒绝服务攻击,也可能是代理滥用)


谢谢你这么精彩的回答!发布的url在使用前会经过一些检查和筛选,主要是因为它要进入数据库,需要先进行清理。再次感谢!
// Careful not to accept just any url anyone sends...
$url = $_POST['url'];