0

我只需要获取当前节点而不是子节点中的图像
我只想获取green/yellow/red/black没有图像的not_important.gif图像
我可以使用查询'.//table/tr/td/img'
但我需要它在循环中

<?php
    /////////////////////////////////////////////////////////////////////
        $html='
            <table>
                <tr>
                    <td colspan="2">
                        <span>
                            <img src="not_important.gif" />
                        </span>
                        <img src="green.gif" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <span>yellow</span>
                        <img src="yellow.gif" />
                    </td>
                    <td>
                        <span>red</span>
                        <img src="red.gif" />
                    </td>
                </tr>
            </table>
            <table>
                <tr>
                    <td>
                        <span>
                            <img src="not_important.gif" />
                        </span>
                        <img src="black.gif" />
                    </td>
                </tr>
            </table>
        ';
    /////////////////////////////////////////////////////////////////////
        $dom = new DOMDocument();
        $dom->loadHTML($html);
        $xpath = new DomXPath($dom);
    /////////////////////////////////////////////////////////////////////
        $query = $xpath->query('.//table/tr/td');
        for( $x=0,$results=''; $x<$query->length; $x++ )
        {
            $x1=$x+1;

            $image = $query->item($x)->getELementsByTagName('img')->item(0)->getAttribute('src');

            $results .= "image $x1 is : $image<br/>";
        }
        echo $results;
    /////////////////////////////////////////////////////////////////////
?>

我能做到吗?$query->item()->
我试过了,has_attributes但 我失败了::getElementsByTagNameNSgetElementById

4

2 回答 2

4

代替:

$image = $query->item($x)->getELementsByTagName('img')->item(0)->getAttribute('src');

...和:

$td = $query->item($x); // grab the td element
$img = $xpath->query('./img',$td)->item(0); // grab the first direct img child element
$image = $img->getAttribute('src'); // grab the source of the image

换句话说,XPath再次使用该对象进行查询,但现在 for ./img,相对于您作为第二个参数提供的上下文节点query()td上下文节点是早期结果的元素 ( ) 之一。

于 2011-08-15T00:42:39.253 回答
1

查询//table/tr/td/img应该可以正常工作,因为不需要的图像都驻留在<span>元素中。

你的循环看起来像

$images = $xpath->query('//table/tr/td/img');
$results = '';
for ($i = 0; $i < $images->length; $i++) {
    $results .= sprintf('image %d is: %s<br />',
                        $i + 1,
                        $images->item($i)->getAttribute('src'));
}
于 2011-08-15T00:38:39.413 回答