【问题标题】:Retrieve the number of 'a' tags between two tags检索两个标签之间的“a”标签的数量
【发布时间】:2013-02-19 15:55:31
【问题描述】:

我想要的是检索特定 <td> 标记之间的 HTML <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 )
)

感谢您的建议。

【问题讨论】:

  • xpath? //td[@bgcolor="#0051AB"]//a?
  • 你能澄清一下你在这里说的话吗?
  • 能否请您详细说明或分享您的示例 html
  • 例子现在有问题

标签: php dom tags


【解决方案1】:

我更喜欢 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();

 } 

【讨论】:

  • 这只是一个想法。 PHP DOMdocument 也可用于实现此功能,但由于对 jquery 语法更熟悉,查询路径更可取。
【解决方案2】:

简单的 HTML DOM 易于使用。

http://simplehtmldom.sourceforge.net/

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多