2011-01-05 43 views
0

我有一個表格嵌套在我用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中的經驗?

我非常希望能夠使用更精確的查詢,並希望能夠保持查詢相對於它而不是絕對的。

回答

0

我想通了。 :)

如果主表標記不存在,php xpath實現不知道如何處理表內部節點(即:tr,td)。

我的外部td標籤​​導致xpath查詢意外的結果。

修改了$ context_nodes查詢:

$context_nodes = $xpath->query('//table[@id="id1"]/tr[position()>1]/td'); 

而且我們好。

+0

我不喜歡它,但它的作品。 – David 2011-01-05 18:48:03

+0

您寫了* php xpath實現不知道如何處理表內部節點*。這是錯誤的。 **你沒有注意到'td'元素**。 – 2011-01-05 19:45:39

+0

@Alejandro不,它似乎是相當真實的,但只有在特定情況下,已從xml中去除了頂層標籤'

...
'。看到原來的問題。 – David 2011-02-23 16:52:40