我有一個表格嵌套在我用php xpath解析的表格中。php xpath表格解析問題
我正在使用一系列xpaths,因爲我將代碼分解爲多個方法調用的概念單元,並且此結構在沒有嵌套表格的其他場景中一直運行良好。
下面的代碼:
// create a host DOM document
$dom = new DOMDocument();
// load the html string into the dom
$dom->loadHTML($html_string);
// make an xpath object out of the dom
$xpath = new DOMXpath($dom);
// run query to extract the rows from the master table
$context_nodes = $xpath->query('//table[@id="id1"]/tr[position()>1]');
// parse data from the individual tables nested in each master table row
foreach($context_nodes as $context_node){
$interesting_nodes[] = $xpath->query('table[2]/tr[td[2]]', $context_node);
}
所得$ interesting_nodes數組包含空DOMNodeLists。
$ context_nodes DOMNodeList包含有效數據。每個$ context_node的HTML內容是這樣的:
<td>
<table></table>
<table>
<tr>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</td>
我嘗試以下簡化$ intesting_nodes查詢匹配的任何表:
$intesting_nodes[] = $xpath->query('table', $context_node);
但仍然產生相同的空DOMNodeLists。
現在最有趣的部分
當我嘗試了$ interesting_nodes查詢,像這樣:
$interesting_nodes[] = $xpath->query('*[2]/*[*[2]]', $context_node);
然後一切都運行完美;但如果我用相應的「表」,「tr」或「td」標記替換的任何「*」,則查詢再次中斷。
有沒有其他人有這種行爲和相對XPath查詢在PHP中的經驗?
我非常希望能夠使用更精確的查詢,並希望能夠保持查詢相對於它而不是絕對的。
我不喜歡它,但它的作品。 – David 2011-01-05 18:48:03
您寫了* php xpath實現不知道如何處理表內部節點*。這是錯誤的。 **你沒有注意到'td'元素**。 – 2011-01-05 19:45:39
@Alejandro不,它似乎是相當真實的,但只有在特定情況下,已從xml中去除了頂層標籤'