SimpleXML - I/O 警告:无法加载外部实体

php
2022-08-30 15:16:33

我正在尝试创建一个小应用程序,该应用程序将简单地读取RSS源,然后在页面上布局信息。

我发现的所有说明都使这看起来过于简单,但由于某种原因,它只是不起作用。我有以下

include_once(ABSPATH.WPINC.'/rss.php');
$feed = file_get_contents('http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int');
$items = simplexml_load_file($feed);

就是这样,然后它在第三行中断并出现以下错误

Error: [2] simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "<?xml version="1.0" encoding="UTF-8"?> <?xm
The rest of the XML file is shown.

我已经打开了allow_url_fopen,并在我的设置中allow_url_include,但仍然一无所获。我尝试过多个 Feed,但最终都得到相同的结果?

我在这里发疯了


答案 1

simplexml_load_file()XML 文件(磁盘上的文件或 URL)解释为对象。你里面的就是一个字符串。$feed

您有两种选择:

  • 用于以字符串形式获取 XML 源,并使用 e simplexml_load_string()file_get_contents()

    $feed = file_get_contents('...');
    $items = simplexml_load_string($feed);
    
  • 使用 simplexml_load_file() 直接加载 XML 源:

    $items = simplexml_load_file('...');
    

答案 2

如果服务器上未启用 cURL,也可以使用 cURL 加载file_get_contents内容。

例:

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$output = curl_exec($ch);

curl_close($ch);

$items = simplexml_load_string($output);

推荐