我希望能做相当于
$html->find("#foo>ul")但是PHP库不识别“直接后代”选择器>,因此在#foo下查找所有<ul>项,包括那些嵌套在#foo中更深的项。
你会推荐什么方法来获取特定类型的直系后代呢?
发布于 2015-10-17 22:17:27
您可以使用DomElementFilter在某些Dom分支下获取所需的节点类型。这里描述了这一点:
PHP DOM: How to get child elements by tag name in an elegant manner?
或者在所有childNodes上执行一个常规循环,然后自己按它们的标记名进行筛选:
foreach ($parent->childNodes as $node)
if ($node->nodeName == "tagname1")
...发布于 2015-10-17 22:06:04
HTML片段
<div id="foo">
<ul>
<li>1</li>
</ul>
<ul>
<li>2</li>
</ul>
<ul>
<li>3</li>
</ul>
</div>获得第一个PHP的<ul>代码
echo $html->find('#foo>ul', 0);这将输出
<ul>
<li>1</li>
</ul>但是如果你想从第一个1得到<ul>
echo $html->find('#foo>ul', 0)->plaintext;发布于 2017-03-07 23:16:04
只为了分享我在相关文章中找到的解决方案,简单地说一句:“用PHP简单DOM解析器查找直接后代”都适用于.
...PHP简单DOM:
//if there is only one div containing your searched tag
foreach ($html->find('div.with-given-class')[0]->children() as $div_with_given_class) {
if ($div_with_given_class->tag == 'tag-you-are-searching-for') {
$output [] = $div_with_given_class->plaintext; //or whatever you want
}
}
//if there are more divs with a given class (better solution)
$all_divs_with_given_class =
$html->find('div.with-given-class');
foreach ($all_divs_with_given_class as $single_div_with_given_class) {
foreach ($single_div_with_given_class->children() as $children) {
if ($children->tag == 'tag-you-are-searching-for') {
$output [] = $children->plaintext; //or whatever you want
}
}
} ...and还包括PHP /xpath:
$all_divs_with_given_class =
$xpath->query("//div[@class='with-given-class']/tag-you-are-searching-for");
if (!is_null($all_divs_with_given_class)) {
foreach ($all_divs_with_given_class as $tag-you-are-searching-for) {
$ouput [] = $tag-you-are-searching-for->nodeValue; //or whatever you want
}
}请注意,您必须在xpath中使用单个斜杠"/“,才能找到直接的后代。
https://stackoverflow.com/questions/33191977
复制相似问题