xpath-> query()仅适用于星号

以下是我目前正在使用的代码。

input的XML文件可以在这里find: http : //pastebin.com/hcQhPSjs

header("Content-Type: text/plain"); $xmlFile = new domdocument(); $xmlFile->preserveWhiteSpace = false; $xmlFile->load("file:///srv/http/nginx/html/xml/UNSD_Quest_Sample.xml"); $xpath = new domxpath($xmlFile); $hier = '//Workbook'; $result = $xpath->query($hier); foreach ($result as $element) { print $element->nodeValue; print "\n"; }; 

现在对于$hiervariables,除非我使用通配符*来到达我需要的节点,否则PHP将不会parsing结果。 所以,而不是使用通常的/Workbook/Worksheet/Table/Row/Cell/Data访问节点的方法,我降级到/*/*[6]/*[2]/*input文件是一个Excel电子表格出口到XML。 似乎这个问题可能在从xls到xml的导出中。

我发现奇怪的是Firefox(默认浏览器)在Chromium和/或任何文本编辑器中不parsing根元素<Workbook>的命名空间属性。
火狐:

 <?mso-application progid="Excel.Sheet"?> <Workbook> <DocumentProperties> <Author>Htike Htike Kyaw Soe</Author> <Created>2014-01-14T20:37:41Z</Created> <LastSaved>2014-12-04T10:05:11Z</LastSaved> <Version>14.00</Version> </DocumentProperties> <OfficeDocumentSettings> <AllowPNG/> </OfficeDocumentSettings> 

铬:

 <?mso-application progid="Excel.Sheet"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> <Author>Htike Htike Kyaw Soe</Author> <Created>2014-01-14T20:37:41Z</Created> <LastSaved>2014-12-04T10:05:11Z</LastSaved> <Version>14.00</Version> </DocumentProperties> <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"> <AllowPNG/> </OfficeDocumentSettings> 

任何人都可以解释为什么这是事实吗?

您需要注册并使用XML中使用的名称空间的名称空间前缀。 从标签和元素名称,我期望它是urn:schemas-microsoft-com:office:spreadsheet – Excel Spreadsheet。 所以这里是一个例子:

 $xml = <<<'XML' <?xml version="1.0"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"> <Worksheet> <Table> <Row> <Cell> <Data>TEST</Data> </Cell> </Row> </Table> </Worksheet> </Workbook> XML; $dom = new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->loadXML($xml); $xpath = new DOMXpath($dom); $xpath->registerNamespace('s', 'urn:schemas-microsoft-com:office:spreadsheet'); $expression = '/s:Workbook/s:Worksheet/s:Table/s:Row/s:Cell/s:Data'; $result = $xpath->evaluate($expression); foreach ($result as $element) { print $element->nodeValue; print "\n"; } 

输出:

 TEST 

你不应该使用DOMXpath::query()而应该使用DOMXpath::query() DOMXpath::evaluate() 。 它允许您使用XPath获取标量值。

 $expression = 'string(/s:Workbook/s:Worksheet/s:Table/s:Row/s:Cell/s:Data)'; echo $xpath->evaluate($expression);