gpt4 book ai didi

php - 如何使用 php 和简单的 html dom 从元素中获取 href

转载 作者:行者123 更新时间:2023-12-02 01:07:27 24 4
gpt4 key购买 nike

我有一个看起来有点像这样的 html 页面

xxxx
<a href="www.google.com">google!</a>

<div class="big-div">
<a href="http://www.url.com/123" title="123">
<div class="little-div">xxx</div></a>

<a href="http://www.url.com/456" title="456">
<div class="little-div">xxx</div></a>
</div>
xxxx

我正在尝试将 href 从 big-div 中拉出来。我可以使用如下代码从整个页面中获取所有 href。

$links = $html->find ('a');
foreach ($links as $link)
{
echo $link->href.'<br>';
}

但是我如何才能只获得 div“big-div”中的 href。编辑:我想我明白了。对于那些关心的人:

foreach ($html->find('div[class=big-div]') as $element) {
$links = $element->find('a');
foreach ($links as $link) {
echo $link->href.'<br>';
}
}

最佳答案

documentation很有用:

$html->find(".big-div")->find('a');

然后继续获取 href 以及您感兴趣的任何其他属性。

编辑: 以上是总体思路。我从未使用过 Simple HTML DOM,因此您可能需要稍微调整一下语法。尝试:

foreach($html->find('.big-div') as $bigDiv) {
$link = $bigDiv->find('a');
echo $link->href . '<br>';
}

或者也许:

$bigDivs = $html->find('.big-div');

foreach($bigDivs as $div) {
$link = $div->find('a');
echo $link->href . '<br>';
}

关于php - 如何使用 php 和简单的 html dom 从元素中获取 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20962267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com