如何在php中加载一个xml文件,以便在上面使用xpath


How to load a xml file in php so that i can use xpath on it?

我的php有问题,如果我实现下面的代码,那么什么都不会发生。

$filename = "/opt/olat/olatdata/bcroot/course/85235053647606/runstructure.xml";
if (file_exists($filename)) {
 $xml = simplexml_load_file($filename, 'SimpleXMLElement', LIBXML_NOCDATA);
 // $xpath = new DOMXPath($filename);
}
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXpath($doc);
$res = $xpath->query('/org.olat.course.Structure/rootNode/children/org.olat.course.nodes.STCourseNode/shortTitle');
foreach ($res as $entry) {
    echo "{$entry->nodeValue}<br/>";
}

如果我用$filename 的内容更改内容中$xml的内容

$xml = '<org.olat.course.Structure><rootNode class="org.olat.course.nodes.STCourseNode"> ... ';

然后它就工作了,所以我认为加载xml文件的方法有问题,我还尝试将xml文件加载为Domdocument,但它也不起作用。在这两种情况下,如果我通过xml收集xml数据,它确实有效例如,这适用于

echo$Course_name=$xml->rootNode->longTitle;

loadXML采用字符串作为输入,而不是simplexml_load_file的返回值。只需使用file_get_contentsstring的形式获取文件的(完整)内容