从文件加载时使用SimpleXMLElement

时间:2015-12-02 06:28:06

标签: php xml simplexml

我有一个问题让我摸不着头脑,我确信它是一个简单的解决方案,但对于我的生活,我无法找到它。

我试图在PHP中使用XMLReader来计算XML文件的节点。直到现在还没有什么新东西,这里有很多关于如何做到这一点的例子。问题是所有示例都是从表示整个XML文件的字符串加载(simplexml_load_string)。这很好。但是,如果我尝试从文件加载,我会得到预期的#34;& lt;'找不到" SimpleXML的例外。

以下是代码:

$xml = simplexml_load_file($fname); //$fname is a valid xml file, it loads fine
$elem = new SimpleXMLElement($xml); //it chokes on this line

从字符串加载它虽然有效,但我确实想从文件中加载它:

$xml = simplexml_load_string($xmlstring); //$xmlstring is the content of the same xml file

我错过了什么?谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

simplexml_load_file 将XML文件解释为xml对象,因此$ xml本身就是一个xml对象,要访问它的元素只需使用$ xml对象属性,无需创建新对象$ elm < / p>

  

simplexml_load_file返回类SimpleXMLElement的对象,其属性包含XML文档中保存的数据,或者失败时为FALSE。

http://php.net/manual/en/function.simplexml-load-file.php