[英]php xpath table parsing question
我在使用php xpath解析的表中嵌套了幾個表。
我使用了一系列xpath,因為我正在通過幾個方法調用將代碼分解為概念單元,並且這種結構在沒有嵌套表的其他情況下也可以正常工作。
這是代碼:
// 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”標記替換任何 “ *”,則查詢將再次中斷。
有沒有其他人有這種行為的經驗和PHP中的相對xpath查詢?
我非常希望能夠使用更精確的查詢,並且希望能夠像這樣保持相對的查詢,而不是使其絕對。
我想到了。 :)
如果不存在主表標簽,則php xpath實現不知道如何處理表內部節點(即:tr,td)。
我的外部td標簽導致xpath查詢產生意外結果。
將$ context_nodes查詢修改為:
$context_nodes = $xpath->query('//table[@id="id1"]/tr[position()>1]/td');
而且我們很好。
我認為您可能需要在后續查詢中使用相對路徑(以。 開頭 ),請參閱http://php.net/manual/en/domxpath.query.php#99760
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.