Reputation: 85
What I want is to retrieve the number of HTML <a>
tags that are between specific <td>
tag.
The example is what I have but I don't know how to put the rest in code..
$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>
}
Example
<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
The result I need: (0 = name of the td nodeValue, 1 = number of tags before the next node)
Array => (
Array[0] => ([0] => Project1, [1] => 2 ),
Array[1] => ([0] => Project2, [1] => 1 )
)
Thanks for your advice.
Upvotes: 0
Views: 114
Reputation: 484
Simple HTML DOM is easy to use.
http://simplehtmldom.sourceforge.net/
foreach($html->find('td') as $td) {
$td_value = $td->plaintext;
foreach($td->find('a') as $anchor) {
...
}
}
Upvotes: 2
Reputation: 895
I'll prefer QueryPath For This Requirement over PHP DOM; Why? it's different discussion.
Below Is the solution of your problem.
Download QueryPath And Just include in your PHP file.
require("../../QueryPath\QueryPath.php");
Following Is the example HTML for Parsing
$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>";
Code To Parse 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();
}
Upvotes: 3