【问题标题】:Get href value from matching anchor text从匹配的锚文本中获取 href 值
【发布时间】:2013-01-29 18:02:19
【问题描述】:

我对 DOMDocument 类还很陌生,似乎无法为我正在尝试做的事情找到答案。

我有一个大的 html 文件,我想从基于锚文本的元素中获取链接。

例如

$html = <<<HTML
<div class="main">
    <a href="http://link.com" target="blank" ><span><font style="color: #e7552c;"><img src="http://images.com/spacer.gif"/>Keyword</font></span></a>
    other text
</div>
HTML;

// domdocument
$doc = new DOMDocument();
$doc->loadHTML($html);

我想获取任何具有文本关键字的元素的 href 属性值。希望这很清楚

【问题讨论】:

  • 您的 HTML 无效:1 &lt;div&gt; 和 2 &lt;/div&gt;s
  • 为自己的目的开发正则表达式...
  • 它是一个较大的 html 文件的一部分,在发布之前忘记删除额外的 div。进行了更改。

标签: php html-parsing domdocument


【解决方案1】:
$html = <<<HTML
<div class="main">
    <a href="http://link.com" target="blank" ><span><font style="color: #e7552c;"><img src="http://images.com/spacer.gif"/>Keyword</font></span></a>
    other text
</div>
HTML;

$keyword = "Keyword";

// domdocument
$doc = new DOMDocument();
$doc->loadHTML($html);
$as = $doc->getElementsByTagName('a');
foreach ($as as $a) {
    if ($a->nodeValue === $keyword) {
        echo $a->getAttribute('href'); // prints "http://link.com"
        break;
    }
}

【讨论】:

  • 那个丑陋的内部for 循环的原因是什么?为什么不简单地$a-&gt;getAttribute('href')
猜你喜欢
  • 2013-03-04
  • 1970-01-01
  • 2015-03-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多