Php DOMELENT对象-指定我需要哪个同级?
有没有更整洁/更好的方法遍历我的DomeElement对象 特别是,当我希望获得值4、5和6时,我认为一定有比Php DOMELENT对象-指定我需要哪个同级?,php,xpath,domxpath,Php,Xpath,Domxpath,有没有更整洁/更好的方法遍历我的DomeElement对象 特别是,当我希望获得值4、5和6时,我认为一定有比->nextSibling->nextSibling->nextSibling->nextSibling->nextSibling等更好的方法来获取节点。。。?是否有一种方法可以让我指定所需的兄弟姐妹 public function fire() { $url = "http://test.com"; $html = $this->downloadPage($url
->nextSibling->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> </td> // Dont Want
<td colspan="3" align="right"></td> // Dont Want
</tr>
</table>
//不要
//不要
//不要
//不要
//不要
是
aaa//Value1
bbb//Value2
ccc//Value3
颗粒物
ddd//Value4
eee//Value5
fff//Value6
//我想要这个日期的评论
//不要
//不要
我不完全清楚您到底需要什么,但听起来您希望从带有定价类的单元格中获取值,并获取更新的注释
// 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);
aah,谢谢你。我试着做类似的事情,但失败了。没有->项(0)
,在第一个xpath查询中,我无法运行第二个xpath查询。所以我认为这是不可能的。谢谢你的帮助。为了让问题更清楚,我重新措辞了。有没有一种方法可以指定特定子节点的节点值而不是遍历?例如,从您的示例中:是否可以执行以下操作,而不是foreach,$pricings->item(3)->nodeValue
?是的,类似这样。$pricings
变量是一个(表示DOM节点的集合)。该方法检索单个节点,在您的情况下,该节点将是一个对象,因此您可以访问其属性。请记住,提供给item()
的数字是以零为基础的。