SimpleXML解析外部php feed

时间:2013-04-03 09:28:06

标签: php xml simplexml feed feedparser

我想解析外部php feed。 地址:http://www.hittadjur.se/feed.php?count=1

输出:

<?xml version="1.0"?>
<annons>
<rubrik>Wilja</rubrik>
<datum>2013-03-22</datum>
<ras>Chihuahua långhår</ras>
<ort>Göteborg</ort><bildurl>http://www.hittadjur.se/images/uploaded/thumbs/1363984467.jpg</bildurl><addurl>http://www.hittadjur.se/index.php?page=case&type=&county=32&subpage=show&case=1363984558</addurl>
</annons>

我的PHP代码不起作用:

$content = utf8_encode(file_get_contents('http://www.hittadjur.se/feed.php?count=1'));
$xml = simplexml_load_file($content);
echo $xml->annons->rubrik;

我使用utf8_encode的原因是,如果我不这样做,我会收到此消息:

parser error : Input is not proper UTF-8, indicate encoding ! Bytes: 0xE5 0x6E 0x67 0x68

现在的错误是:

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity 有任何想法吗? 谢谢!

3 个答案:

答案 0 :(得分:0)

如果您尝试加载服务器上保存的xml,请尝试传递完整目录路径

simplexml_load_file($_SERVER['DOCUMENT_ROOT'].'/example.xml')

或者如果你想通过http协议访问xml,你需要在php.ini或

中设置allow_url_fopen ON
ini_set('allow_url_fopen ','ON');
你的代码中的

。或者如果你使用的是php版本&lt; 5

,你也可以这样做
$temp = file_get_contents($url);
 $XmlObj = simplexml_load_string($temp); 

答案 1 :(得分:0)

我担心Feed会提供格式错误的XML。除了编码混乱:

<addurl>http://www.hittadjur.se/index.php?page=case&type=&county=32&subpage=show&case=1363984558</addurl>
                                                   ^
                                                   \_ Data not properly escaped

我可能错了,但我不认为你可以使用常规XML函数解析它,因为它们是为有效的XML而设计的(这首先是使用XML的全部目的)。

也许你可以试试DOMDocument。它是为HTML设计的,因此它可以处理无效输入,但也可以处理XML。

编辑:这是a trick to fix invalid XML,但老实说,我不确定这是值得的。

答案 2 :(得分:0)

像alvaro vicario所写,问题是你的网址中的参数分隔符(&)。在xml中,&符是实体标记(=命名符号的开头(序列)或字符代码点的数字表示),必须进行转义。

在您的网址中将&替换为&amp;,或将网址标记为文字文字(xml中的CDATA部分):<![CDATA[http://...]]>

例如。 :<addurl><![CDATA[http://www.hittadjur.se/index.php?page=case&type=&county=32&subpage=show&case=1363984558]]></addurl>

如果您对代码中的快速utf8转换感到不舒服并且您知道数据源的字符编码,则可以增强xml序言(iso-8859-1包含有问题的å / {{1你的xml):

0xE5
相关问题