检查不同的节点并相应地回显

时间:2016-06-10 08:25:31

标签: php xpath

我的页面索引具有略微不同的结构。我正在尝试遍历许多页面并执行以下操作: -

1.if td[2]具有跨越类以响应该类。 2.如果td[2]有img节点,则计算src http://example.com/img/star01.giff <tbody> <tr> <td>Name1</td> <td> <span class="star5-05"> </td> </tr> <tr> <td>Name2</td> <td> <span class="star5-05"> </td> </tr> </tbody> 的节点数并回显总数。

我能够完成第一部分而不是第二部分。

pagetype1

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

pagetype2

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>";
            }

        }

    }

我的代码

./changefilesize data.txt 100

1 个答案:

答案 0 :(得分:0)

实际上,unswer是Xpath count(.//img[@src="http://example.comimg/star01.gif"])。所有代码仅用于测试目的

$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(对于不同的xml更改为str1或str))