我将此代码放入 $html 变量中:
...
...
<table id="tbvalue" class="table_main">
<tr align="center">
<td>
<div style='background-color:#534522;' ><img src="operation.bmp" border="0" alt="image" width="250" height="60" /></div>
<br />
</td>
</tr>
<tr align="center">
<td class="other">
more text
</td>
</tr>
<tr align="center">
<td>
<input name="name" type="text" id="label" tabindex="1"/>
</td>
</tr>
<tr>
<td>
<span id="lblErrCap" class="errfont"></span>
</td>
</tr>
</table>
...
...
注意:我需要第一次出现 <img>
位于 table id="tbvalue"
内部
我试图这样做:
$dom = new domDocument;
/*** load the html into the object ***/
@$dom->loadHTML($html); // the @ is to silence errors and misconfigures of HTML
/*** discard white space ***/
$dom->preserveWhiteSpace = false;
$xpath = new DOMXPath($dom);
$spans = $xpath->query('//img');
echo $spans->item(0)->getAttribute("src");
但是这个查询不了解表 table id="tbvalue"
并且只需采用第一个 <img>
。
获得第一个 img
的方法是什么? 里面 table id="tbvalue"
?
最佳答案
这样做:
<?php
$xpath = new DOMXPath($dom);
$spans = $xpath->query('//table[@id="tbvalue"]//img[1]');
echo $spans->item(0)->getAttribute("src");
//
运算符表示从当前节点中选择文档中与选择匹配的节点,无论它们位于何处
更多有用信息您可以找到here .
关于php - 使用 domDocument 和 DOMXPath 解析 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27745147/