PHP DOM解析以获取特定div id中的元素 [英] PHP DOM parsing to get to elements inside specific div id
问题描述
我有一些html,如下所示:
I have some html as follows:
<div id="tvcap">
<div class="c" id="tads">
<ol>
<li>
<div class="vsc vsta">
<h3>
<a id="pa1" href="">
</a>
<a id="vpa1" href="http://www.link1.com">
Link 1 Text 1</a>
</h3>
<div>
<div class="kv kva">
<cite>
www.link1.com</cite>
</div>
</div>
<span class="ac">Link 1 Text2</span>
</div>
</li>
<li>
<div class="vsc vsta">
<h3>
<a id="pa2" href="">
</a>
<a id="vpa2" href="http://www.link2.com">Link 2 Text 1</a>
</h3>
<div>
<div class="kv kva">
<cite>www.link2.com</cite>
</div>
</div>
<span class="ac">Link 2 Text 3</span>
<div>
<div class="oslk">
</div>
</div>
</div>
</li>
</ol>
</div>
</div>
潜在地将有一个未知数量的链接和文本,我希望迭代和能够获取每个链接和文本。
Potentially there will be an unknown number of the links&texts, and I wish to iterate and be able to get to each link and text.
我正在使用简单html dom解析器。
我找不到命令来获取div id'vpa1'。
I cannot find the command to get to the div id 'vpa1'.
我尝试过这个,但是没有返回:
I tried this, but it returns nothing:
foreach($html->find('a') as $element)
if ($element->id == "vpa1") echo $element->href . '<br>';
如何获取每个链接和基于id的文本vpa [$ i](vpa1 ,vpa2等)。
How can I get to each link and text based on the id being vpa[$i] (vpa1, vpa2, etc).
推荐答案
从任何网页提取特定div id的内容的功能
以下函数从指定的div中提取内容并返回。如果没有找到具有ID的div,它将返回false。
The below function extracts the contents from the specified div and returns it. If no divs with the ID are found, it returns false.
function getHTMLByID($id, $html) {
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$node = $dom->getElementById($id);
if ($node) {
return $dom->saveXML($node);
}
return FALSE;
}
$ id
的内容,您的HTML标记< div>
$id
is the ID of the <div>
whose content you're trying to extract, $html
is your HTML markup.
使用示例:
$html = file_get_contents('http://www.mysql.com/');
echo getHTMLByID('tagline', $html);
输出:
The world's most popular open source database
这篇关于PHP DOM解析以获取特定div id中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!