DomElement对象 - 指定我需要哪个兄弟?

时间:2013-10-18 11:37:47

标签: php xpath domxpath

是否有更简洁/更好的遍历我的DomElement对象的方式?

特别是,当我想要获得值4,5和6时,我认为必须有比->nextSibling->nextSibling->nextSibling->nextSibling等更好的获取节点的方法......?有没有一种方法可以让我指定我需要的兄弟姐妹?

public function fire()
{
    $url = "http://test.com";
    $html = $this->downloadPage($url);

    $doc = new DOMDocument();
    @$doc->loadHTML($html);

    $xpath = new DOMXpath($doc);

    $myXpath = $xpath->query('//*[@id="test_table"]');

    if (!is_null($myXpath)) 
    {
        $domElement = $myXpath->item(0);
            $parent = $domElement->firstChild->nextSibling->nextSibling->firstChild->nextSibling;
            $value1 = $parent->nodeValue;
            $value2 = $parent->nextSibling->nodeValue;
            $value3 = $parent->nextSibling->nextSibling->nodeValue;

            $this->info("Value 1: " . $value1);
            $this->info("Value 2: " . $value2);
            $this->info("Value 3: " . $value3);
    }
    else {
        $this->info("Error");
    }
}

该表具有以下结构

<table id="test_table">
    <tr>
        <td width="40"></td> // Dont Want
        <td width="55"></td> // Dont Want
        <td width="55"></td> // Dont Want
        <td width="55"></td> // Dont Want
    </tr>
<!--A comment--> // Dont Want
    <tr>
        <td>AM</td>
        <td class="pricing">aaa</td>  // Value1
        <td class="pricing">bbb</td>  // Value2
        <td class="pricing">ccc</td>  // Value3
    </tr>
    <tr>
        <td>PM</td>
        <td class="pricing">ddd</td>  // Value4
        <td class="pricing">eee</td>  // Value5
        <td class="pricing">fff</td>  // Value6
    </tr>
<!--Updated 10:31 18/10/2013--> // I want this date comment
    <tr>
        <td>&nbsp;</td> // Dont Want
        <td colspan="3" align="right"></td> // Dont Want
    </tr>
</table>

1 个答案:

答案 0 :(得分:1)

我并不完全清楚你究竟需要什么,但听起来你想要从pricing类的单元格中获取值并获得Updated注释。< / p>

// Get the table, to use as a context node for the other queries
$table = $xpath->query('//table[@id="test_table"]')->item(0);

// Get cells with class="pricing"
$pricings = $xpath->query('descendant::td[@class="pricing"]', $table);
foreach ($pricings as $pricing) {
    // E.g. $text = $pricing->nodeValue;
    var_dump($doc->saveXML($pricing));
}

// Get the "Updated ..." comment
$updated_query = 'string(descendant::comment()[starts-with(., "Updated ")])';
$updated = $xpath->evaluate($updated_query, $table);
var_dump($updated);

See this example's output