2013-02-19 65 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