【问题标题】:how to check if a tag with specific title attribute is present in html by ganon in php如何通过php中的ganon检查html中是否存在具有特定标题属性的标签
【发布时间】:2018-04-08 17:28:34
【问题描述】:

这是我的代码,其中 raw 包含一个 HTML 字符串,该字符串具有许多具有不同标题属性的“a href”标记,我想检查该字符串是否具有标题为“x”的超链接标记。如何在 PHP 中使用 Ganon HTML dom 解析器来做到这一点。

function store($raw, $link)
{
    $html = str_get_dom($raw);
    if ($html has a href tag with title = "x")
    {
        $anchor = $html('a[title = x]')->getPlainText();
        foreach($anchor as $abc)
        {
            echo $abc->title."<br>";
        }
    }
}

【问题讨论】:

  • 没听说过Ganon,不能只用原生的domdocument解析器吗?
  • 我尝试过原生的,但是我没有找到一种方法来通过原生的标题来获取标签,所以我很久以前就切换到了 ganon。我已经在所有地方都使用过 ganon ......我不想再改变它了。但你至少可以给我一个答案……@chris85……
  • 加农我不能。使用 domdocument,您只需拉取 a 元素,然后查看 title 属性。
  • 您能否提供一些示例 html 以及如何调用 store()

标签: php html parsing dom ganon


【解决方案1】:

您应该能够执行以下操作,但不确定您想要做什么,但这基本上会查找带有 title 属性的 &lt;a&gt;,这是您传入的属性 ($link),然后输出此标签的 href 属性。倒过来倒是很容易,但主要是如何通过属性值找到某个东西,然后显示元素的其他部分的逻辑。

function store($raw, $link)
{
    $html = str_get_dom($raw);
    $anchor = $html('a[title = "'.$link.'"]');
    foreach($anchor as $abc)
    {
        echo $abc->href."<br>";
    }
}

$html = <<< HTML
<html><a href='abc' title='firsttitle'>linkxrefabc</a>
<a href='xref' title='title2'>linkxref</a></html>
HTML;

store($html, 'firsttitle');   // outputs abc<br>

store($html, 'title2');  // outputs xref<br>

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 2012-12-13
    • 2020-02-09
    • 2014-01-17
    • 2016-04-15
    • 2021-04-25
    • 2017-06-19
    • 2019-04-30
    相关资源
    最近更新 更多