[英]xpath->query() works only with asterisks
以下是我目前正在使用的代碼。
輸入的XML文件位於以下位置: 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";
};
現在,對於$hier
變量,除非使用通配符*
到達所需的節點,否則PHP不會解析結果。 因此,我不再使用訪問節點的通常的/Workbook/Worksheet/Table/Row/Cell/Data
方法,而是使用/*/*[6]/*[2]/*
輸入文件是導出的excel電子表格到xml。 似乎問題出在從xls到xml的導出中。
我發現奇怪的是,Firefox(默認瀏覽器)不解析Chromium和/或任何文本編輯器所做的根元素<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電子表格。 因此,這是一個示例:
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.