【问题标题】:Can't load the XML file?无法加载 XML 文件?
【发布时间】:2014-05-21 12:47:47
【问题描述】:

http://westwood-backup.com/podcast?categoryID2=403

这是我想通过 PHP 加载和回显的 XML 文件。我尝试了 file_get_contents 并加载。两者都返回空字符串。如果我将 URL 更改为另一个 XML 文件,则函数效果很好。 URL 有什么特别之处?

<?php 
$content = file_get_contents("http://westwood-backup.com/podcast?categoryID2=403");
echo $content;
?>

再次尝试加载,同样的空结果。

<?php 
$feed = new DOMDocument();
if (@$feed->load("http://westwood-backup.com/podcast?categoryID2=403")) { 
    $xpath = new DOMXpath($feed);
    $linkPath = $xpath->query("/rss/channel/link");
    echo $linkPath
}
?>

【问题讨论】:

  • 开启错误报告并在屏幕上显示错误。 error_reporting(E_ALL); ini_set('display_errors', 1); 你会看到请求失败。可能他们正在阻止来自某些 http 用户代理的请求。
  • @MichaelBerkowski 对。捕获错误“无法打开流:HTTP 请求失败!”我怎样才能超越这个限制?
  • 有趣的是,使用 http 流包装器的 file_get_contents() 对我来说立即失败。在 PHP 中使用curl_exec(),它会挂起并且永远不会返回响应。如果我在命令行中使用curl,它会立即返回正确的响应。
  • 如果您在 curl 中执行此操作并设置超时 + 用户代理,则它可以工作。请参阅下面的答案。

标签: php xml file-get-contents


【解决方案1】:

使用 CURL,你可以这样做:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://westwood-backup.com/podcast?categoryID2=403');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, ' Mozilla/1.22 (compatible; MSIE 2.0d; Windows NT)');
$xml = curl_exec($ch);
curl_close($ch);

$xml = new SimpleXMLElement($xml);
echo "<pre>";
print_r($xml);
echo "</pre>";

输出:


我认为服务器实现了“用户代理”检查以确保 XML 数据仅在浏览器中加载(而不是通过 bots/file_get_contents 等...)

因此,通过使用 CURL 并设置一个虚拟用户代理,您可以绕过检查并加载数据。

【讨论】:

    【解决方案2】:

    您需要设置服务器满意的用户代理标头。不想用cUrl就不用了,可以用stream_context_create和file_get_contents:

    $options = array(
            'http'=>array(
                'method'=>"GET",
                'header'=>"Accept-language: en\r\n" .
                    "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad
            )
        );
    
    $context = stream_context_create($options);
    $content = file_get_contents("http://westwood-backup.com/podcast?categoryID2=403", false, $context);
    echo $content;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-01
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多