无法加载XML文件?

时间:2014-05-21 12:47:48

标签: php xml file-get-contents

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
}
?>

2 个答案:

答案 0 :(得分:2)

使用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>";

输出:

enter image description here


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

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

答案 1 :(得分:1)

您需要设置服务器满意的用户代理标头。如果您不想使用它,则无需使用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;
相关问题