检索两个标签之间的'a'标签数量

时间:2013-02-19 15:55:32

标签: php dom tags

我想要的是检索特定<a>代码之间的HTML <td>代码的数量。

这个例子就是我所拥有的,但我不知道如何将其余部分放在代码中。

 $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 )
)

感谢您的建议。

2 个答案:

答案 0 :(得分:3)

我更喜欢QueryPath这个要求而不是PHP DOM;为什么?这是不同的讨论。

以下是问题的解决方案。

下载QueryPath并只包含在您的PHP文件中。

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

以下是用于解析的示例HTML

$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();

 } 

答案 1 :(得分:2)

简单的HTML DOM易于使用。

http://simplehtmldom.sourceforge.net/

foreach($html->find('td') as $td) {
       $td_value = $td->plaintext;
      foreach($td->find('a') as $anchor) {
            ...
      }
}