2010-09-28 78 views
0

我有一个问题读取XML的饲料 示例XML文件:的SimpleXML返回空元素

<f:feed xmlns:f="http://www.bbgo.de/feedxml/feed" xmlns:a="http://www.bbgo.de/feedxml/article" xmlns="http://www.w3.org/1999/xhtml" f:customer="blub" f:name="dax-tecdax"> 
<f:title>Analysen: DAX, TecDAX</f:title> 
<f:date>2010-09-22T20:46:29+02:00</f:date> 
<f:url>http://www.bbgo.de/export/feed/stock-channel/dax-tecdax</f:url> 
<f:articles> 
<a:article a:id="2310446" a:status="published" a:payed-content="false" xml:lang="de-DE"> 
<a:title>Kabel Deutschland mit Verkaufsempfehlung</a:title>... 

一个简单的测试,如:

$feed = new SimpleXMLElement($xml); 
print_r($feed); 

产生

SimpleXMLElement Object () 

如果我尝试

echo $xml; 

以上示例正确回显。

为什么$ feed数组未被构建?我如何访问<f:articles>中的所有<a:article>

+0

没有人有任何想法!? :-( – kritop 2010-10-01 14:16:26

回答

0

如何访问<f:articles>中的所有<a:article>

对我来说simpleXML在处理命名空间时似乎有点笨拙(但是再次说明,我不是PHP编码器)。你可以使用children方法,但在我看来使用XPath更简单。

$feed->registerXPathNamespace('f', 'http://www.bbgo.de/feedxml/feed'); 
$feed->registerXPathNamespace('a', 'http://www.bbgo.de/feedxml/article'); 
$article = feed->xpath("/f:feed/f:articles/a:article"); 

首先,你需要一些前缀注册的名称空间(前缀不需要匹配XML文档中使用的那些,但名称空间URI必须匹配),然后在你的XPath表达式选择使用这些前缀您目标。没有元素名称前缀,XPath表达式将查找不在任何名称空间中的元素。

为什么不建立$ feed数组?

很难猜出原因。有些东西你可以测试:

  • 是字符串$xml一个良好的XML文档
  • 不使用simplexml_load_file($yourXMLfile);simplexml_load_string($yourXMLstring);
创建具有明确的字符串参数工作,一个SimpleXMLElement $feed = new SimpleXMLElement('<root><child/></root>');
  • 你可以加载文档