有没有办法抓取部分匹配的ID的所有元素。例如,如果我想抓取网页上的所有HTML元素,并且id属性以msg_
开头,但可能是之后的任何内容。PHP DomDocument - getElementByID(部分匹配)如何?
这是我走这么远:
$doc = new DomDocument;
// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->loadHtml(file_get_contents('{URL IS HERE}'));
foreach($doc->getElementById('msg_') as $element) {
foreach($element->getElementsByTagName('a') as $link)
{
echo $link->nodeValue . "\n";
}
}
但我需要弄清楚如何做一个局部的ID匹配与该位:$doc->getElementById('msg_')
或者是否有其他方式来做到这一点...?
基本上,我需要抓住所有“A”标记,是从1开始msg_
id为元素的儿童技术上总是有,只是,将是1个a
标签,但我不知道该怎么随便抓第一个孩子,这就是为什么我也使用foreach。
这是可能与DomDocument PHP类?
这是我现在使用的代码,它不工作,要么:
$str = '';
$filename = 'http://dream-portal.net/index.php/board,65.0.html';
@set_time_limit(0);
$fp = fopen($filename, 'rb');
while (!feof($fp))
{
$str .= fgets($fp, 16384);
}
fclose($fp);
$doc = new DOMDocument();
$doc->loadXML($str);
$selector = new DOMXPath($doc);
$elements = $selector->query('//row[starts-with(@id, "msg_")]');
foreach ($elements as $node) {
var_dump($node->nodeValue) . PHP_EOL;
}
HTML如下(它在span
标签):
<td class="subject windowbg2">
<div>
<span id="msg_6555">
<a href="http://dream-portal.net/index.php?topic=834.0">Poll 1.0</a>
</span>
<p>
Started by
<a href="http://dream-portal.net/index.php?action=profile;u=1" title="View the profile of SoLoGHoST">SoLoGHoST</a>
<small id="pages6555">
«
<a class="navPages" href="http://dream-portal.net/index.php?topic=834.0">1</a>
<a class="navPages" href="http://dream-portal.net/index.php?topic=834.15">2</a>
»
</small>
with 963 Views
</p>
</div>
</td>
这是<span id="msg_
部分,还有一堆(HTML页面上至少有15个)。
不要用的loadXML()加载HTML,使用loadHTML() – 2013-04-27 04:30:23
谢谢,这似乎已经摆脱了错误的,然而,仍然是空白... – 2013-04-27 04:35:48
然后,我会建议张贴一部分的HTML以及。 – 2013-04-27 04:37:55