【问题标题】:SimpleXML - I/O warning : failed to load external entitySimpleXML - I/O 警告:未能加载外部实体
【发布时间】:2017-09-15 05:22:50
【问题描述】:

我正在尝试创建一个小型应用程序,它可以简单地读取 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 但仍然没有。 我尝试了多个提要,但最终都得到相同的结果?

我要疯了

【问题讨论】:

  • simplexml_load_file() 需要文件名!对已加载的数据使用simplexml_load_string()
  • 如此简单但又如此有效..谢谢

标签: php


【解决方案1】:

simplexml_load_file()XML 文件(磁盘上的文件或 URL)解释为对象。 $feed 中的内容是一个字符串。

你有两个选择:

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

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

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

【讨论】:

  • 关于使用 file_get_contents() 的说明。我遇到了同样的错误(I/O 警告:无法加载外部实体)并发现它是由我的 PHP 配置引起的。检查 php.ini 中的 upload_max_filesize 和 post_max_size 并确保它们至少与您尝试解析的文件一样大。
【解决方案2】:

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

例子:

$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);

【讨论】:

    【解决方案3】:

    这也有效:

    $url = "http://www.some-url";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $xmlresponse = curl_exec($ch);
    $xml=simplexml_load_string($xmlresponse);
    

    然后我只运行一个 forloop 从节点中获取内容。

    像这样:`

    for($i = 0; $i < 20; $i++) {
    $title = $xml->channel->item[$i]->title;
    $link = $xml->channel->item[$i]->link;
    $desc = $xml->channel->item[$i]->description;
    $html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
    }
    echo $html;
    

    ***请注意,您的节点名称显然会有所不同..您的 HTML 结构可能不同...您的循环也可能设置为更高或更低的结果数量。

    【讨论】:

      【解决方案4】:
      $url = 'http://legis.senado.leg.br/dadosabertos/materia/tramitando';
      $xml = file_get_contents("xml->{$url}");
      $xml = simplexml_load_file($url);
      

      【讨论】:

      猜你喜欢
      • 2017-10-20
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 2012-08-28
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      相关资源
      最近更新 更多