2013-02-19 75 views
0

我想要的是檢索特定<td>標籤之間的HTML <a>標籤的數量。檢索兩個標籤之間'a'標籤的數量

的例子是我,但我不知道如何把代碼中的休息..

$dom = new DOMDocument(); 
$dom->loadHTML($text); 
$i = 0; 
foreach($dom->getElementsByTagName("td") as $node){ 
//Retrieve every TD tag that have the attribute bgcolor = #0051AB 
//<td bgcolor=#0051AB> NODEVALUE </td> 
    if($node->getAttribute("bgcolor") == "#0051AB"){ 
    $cat[]= $node->nodeValue; 
    } 
//HERE identify every 'a' html tag that are between the $node and the next one!! 
//<a href="path">nodeValue</a> 


} 

<table><tr><td bgcolor=#0051AB>Project 1</td></tr></table> 
<a>link1</a> 
other tags and text.. 
<a>Link 2</a> 
enter code here 
<table><tr><td bgcolor=#0051AB>Project 2</td></tr></table> 
codecodecode 
<a>link3</a> 
codecodecode 

結果我需要:(0 =名稱td nodeValue,1 =下一個節點之前的標籤數量)

Array => (
    Array[0] => ([0] => Project1, [1] => 2), 
    Array[1] => ([0] => Project2, [1] => 1) 
) 

感謝您的建議。

+0

的XPath? '// TD [@bgcolor = 「#0051AB」] // A'? – 2013-02-19 15:58:42

+0

你能澄清你在這裏說什麼嗎? – 2013-02-19 16:10:25

+0

可否請您詳細說明一下或分享您的示例html – 2013-02-19 17:08:36

回答

3

我更喜歡QueryPath針對PHP DOM的這個需求;爲什麼?這是不同的討論。

下面是您的問題的解決方案。

下載QueryPath並只包含在您的PHP文件中。

require("../../QueryPath\QueryPath.php"); 

以下是解析

$text="<body> 
<table><tr><td bgcolor=#0051AB>Project 1</td></tr></table> 
<a>link1</a> 
other tags and text.. 
<a>Link 2</a> 
enter code here 
<table><tr><td >Project 2</td></tr></table> 
codecodecode 
<a> Should Not Be Included</a> 
codecodecode 
<table><tr><td bgcolor=#0051AB>Project 2</td></tr></table> 
codecodecode 
<a>link3</a> 
codecodecode</body>"; 

代碼來解析HTML

$tags=htmlqp($text,'body')->children(); 
$isRequiredTag=false; 
$i=0; 
foreach($tags as $pr) 
{ 
$tag= $pr->tag(); 
if($tag=='table'){ 
$isRequiredTag= (htmlqp($text,$tag)->eq($i)->find('td')- >attr('bgcolor')=='#0051AB')?"TRUE":"FALSE"; 
$i++; 
} 

if ($isRequiredTag=="TRUE" && $tag=='a') echo $pr->text(); 

} 
+0

這只是一個想法。 PHP DOMdocument也可以用來實現這個功能,但由於jQuery語法更加貼心,querypath更可取。 – 2013-02-20 10:39:00