sonia k sonia k - 9 months ago 33
PHP Question

check different nodes and echo accordingly

i have index of pages with slight different structure.i am trying to loop through many pages and to do following:-

1.if

td[2]
has span class thn to echo the class.
2.if
td[2]
has img nodes then to count the number of nodes having
src
of
http://example.com/img/star01.giff
and to echo the total.

i am able to do the 1st part but not the 2nd.

pagetype1

<tbody>

<tr>
<td>Name1</td>
<td>
<span class="star5-05">
</td>
</tr>
<tr>
<td>Name2</td>
<td>
<span class="star5-05">
</td>
</tr>
</tbody>


pagetype2

<tbody>
<tr>
<td>Name1</td>
<td>
<img alt="" src="http://example.com/img/star01.gif">
<img alt="" src="http://example.com/img/star01.gif">
<img alt="" src="http://example.com/img/star01.gif">
<img alt="" src="http://example.com/img/star01.gif">
<img alt="" src="http://example.com/img/star02.gif">
</td>
</tr>
<tr>
<td>Name2</td>
<td>
<img alt="" src="http://example.comimg/star01.gif">
<img alt="" src="http://example.comimg/star01.gif">
<img alt="" src="http://example.comimg/star01.gif">
<img alt="" src="http://example.comimg/star01.gif">
<img alt="" src="http://example.com/img/star02.gif">
</td>
</tr>
</tbody>


my code

foreach( $my_nodes as $my_node )
{
$tmp=$my_xpath->query('td[1]',$my_node);

if ($tmp->length>0)
{
$tmp=$tmp->item(0)->textContent;

if ($tmp=="Name1")
{
$chkstars=$my_xpath->query('td[2]/span/@class',$my_node);
if ($chkstars->length>0)
{
$tmp_stars=$chkstars->item(0)->textContent;
}
else
{
$tmp_stars=$my_xpath->evaluate('count(//td[2]/img[@src="http://www.example.com/img/star01.gif"]),$my_node )');
}
echo $tmp_stars."<br>";
}

}

}

Answer Source

In fact, the unswer is Xpath count(.//img[@src="http://example.comimg/star01.gif"]). All the code only for testing purpose

$my_xpath = new DOMXPath($my_doc);
$my_nodes = $my_xpath->query( '//tbody/tr' );  
foreach( $my_nodes as $my_node )
{
$tmp=$my_xpath->query('td[2]',$my_node);
    if ($tmp->length>0)
    {
    $tmp=$tmp->item(0)->textContent;    
        if ($chkstars=$my_xpath->evaluate('string(td[2]/span/@class)',$my_node))
               echo 'class: ' . $chkstars . "\n";
        if($count = $my_xpath->evaluate('count(.//img[@src="http://example.comimg/star01.gif"])',$my‌​_node ))
               echo 'count: ' . $count . "\n";
    }
}

demo (Change to str1 or str for different xml))