[英]php DomXPath - how to get image in current node only and not in child nodes?
[英]php DomXPath - how to select child node from parent node of current node?
我有一個非常重要的問題,對我來說似乎很困難.. 只是我需要從當前節點的父節點到 select 子節點.. 我知道我們使用 (..) 到 select 父節點。 但在我的情況下,這還不夠......這是我的 php 代碼來獲取所有顏色值
<?php
/////////////////////////////////////////////////////////////////////
$html='
<table>
<tr>
<td colspan="2">
<span>green</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>black</span>
<img src="black.gif" />
</td>
</tr>
</table>
';
/////////////////////////////////////////////////////////////////////
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DomXPath($dom);
/////////////////////////////////////////////////////////////////////
$evaluate = $xpath->evaluate('.//table/tr/td/span');
for($x=0,$results=''; $x<$evaluate->length; $x++)
{
$x1=$x+1;
$query1 = $xpath->query('.//table/tr/td/span');
$color = $query1->item($x)->nodeValue;
$results .= "color $x1 is : $color<br/>";
}
echo $results;
/////////////////////////////////////////////////////////////////////
?>
* now i need to get for every color its images src ..
i tried this but no way
<?php
/////////////////////////////////////////////////////////////////////
$html='
<table>
<tr>
<td colspan="2">
<span>green</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>black</span>
<img src="black.gif" />
</td>
</tr>
</table>
';
/////////////////////////////////////////////////////////////////////
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DomXPath($dom);
/////////////////////////////////////////////////////////////////////
$evaluate = $xpath->evaluate('.//table/tr/td/span');
for($x=0,$results=''; $x<$evaluate->length; $x++)
{
$x1=$x+1;
$query1 = $xpath->query('.//table/tr/td/span');
$color = $query1->item($x)->nodeValue;
$query2 = $xpath->query('.//table/tr/td/span['.$x1.']/../img');
$image = $query2->item($x)->getAttribute("src");
$results .= "color $x1 is : $color - and- image $x1 is : $image<br/>";
}
echo $results;
/////////////////////////////////////////////////////////////////////
?>
請幫忙::
嘗試這個:
... initiate/load dom+xpath ...
$res = $xpath->query('//table/tr/td');
foreach($res as $td) {
$spans = $td->getElementsByTagName('span');
$color = $spans[0]->nodeValue;
$imgs = $td->getELementsByTagName('img');
$src = $imgs[0]->getAttribute('src');
}
無需運行兩次完整的 xpath 查詢。 DOM 樹中的每個節點都完全了解其父節點和子節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.