2012-07-18 37 views
0

在相同的HTML pageThere're兩個不同的格式解析HTML頁面相同的兩種不同格式包含:具有上相同的元件

第一是:

<div class="gs"><h3 class="gsr"><a href="http://www.example1.com/">title1</a> 

第二個是:

<div class="gs"><h3 class="gsr"><span class="gsc"></span><a href="http://www.example2.com/">title2</a> 

如何獲得一個代碼中的鏈接和標題,可以使用simple_html_dom處理這兩種不同的格式? 我試過這個代碼,但它不工作:

foreach($html->find('h3[class=gsr]') as $docLink){ 
    $link = $docLink->first_child(); 
    echo $link->plaintext; 
    echo $link->href; 
} 
+0

但你爲什麼問這裏幾乎相同的問題? http://stackoverflow.com/questions/11533705/parsing-title-and-link-from-html-page – Tamil 2012-07-18 11:27:12

+0

@泰米爾是的,我有新的問題。它不同於那個頁面。在上一個問題中,我只是確定了一個html頁面的格式。然後我意識到在相同的元素上有兩種格式。所以我在這裏提出了新的問題。 – 2012-07-18 11:38:24

回答

0

doc似乎有後代選擇器的概念

// Find all <td> in <table> which class=hello 
$es = $html->find('table.hello td'); 

然後

foreach($html->find('h3[class=gsr] a') as $link) { 
    echo $link->plaintext; 
    echo $link->href; 
} 

應該做你的工作。 [我沒有真正意識到simple_html_dom的BTW)只是一種嘗試]

編輯

另外也嵌套選擇

// Find first <li> in first <ul> 
$e = $html->find('ul', 0)->find('li', 0); 

所以

foreach($html->find('h3[class=gsr]') as $docTitle) { 
    $link = $docTitle->find('a', 0); //get the first anchor tag 
    echo $link->plaintext; 
    echo $link->href; 
} 

也應努力

+0

哇,感謝您帶來的概念。有用 !非常感謝你@Tamil :) – 2012-07-18 11:21:53

相關問題