html PHP Dom查找链接href和文本

flvlnr44  于 2023-03-16  发布在  PHP
关注(0)|答案(1)|浏览(120)

html标记之一中,该标记具有:

<ul class="l1nk">
    <li class="dir online">
        <a target="_blank" rel="nofollow" href="https://sample.com/embed/2882015?ref=7Qc" title="ONLINE">
            online
        </a>
    </li>

    <li class="kftfhd">
        <a rel="nofollow" target="_blank" href="https://sample.com/2882015-11-HQ_1080.mp4?ref=7Qc" title="Full HD">Full HD</a>
    </li>

    <li class="kft1080">
        <a rel="nofollow" target="_blank" href="https://sample.com/2882015-11-1080.mp4?ref=7Qc" title="1080p">1080p</a>
    </li>

    <li class="kft720">
        <a rel="nofollow" target="_blank" href="https://sample.com/2882015-11-720.mp4?ref=7Qc" title="720p">720p</a>
    </li>

    <li class="kft480">
        <a rel="nofollow" target="_blank" href="https://sample.com/2882015-11-480.mp4?ref=7Qc" title="480p">480p</a>
    </li>
</ul>

我试图获得链接href与自我文本,如:

https://sample.com/embed/2882015?ref=7Qc

带有ONLINE
我的代码,它不是不正确的是:

$dom = new Dom;
$dom->loadFromUrl("https://sample.org/film/");
$l1nk = $dom->find('.l1nk')->getChildren();

foreach ($l1nk as $data) {
     echo $data->getAttribute('a');
}
wf82jlnq

wf82jlnq1#

$dom = new Dom;
$dom->loadFromUrl("https://sample.org/film/");
$l1nk = $dom->find('.l1nk')->getChildren();

foreach ($l1nk as $data) {
    $a_tag = $data->find('a');

    if (!empty($a_tag)) {
        $link = $a_tag[0]->getAttribute('href');
        $text = trim($a_tag[0]->text());

        echo "$link with $text\n";
    }
}

或者,您可以使用getElementsByTagName()

$dom = new DOMDocument();
$dom->loadHTMLFile("https://sample.org/film/");

$ul = $dom->getElementById("your-ul-id");
$a_tags = $ul->getElementsByTagName("a");

foreach ($a_tags as $a) {
    $href = $a->getAttribute("href");
    $title = $a->getAttribute("title");
    $text = $a->nodeValue;

    echo "Link: $href, Title: $title, Text: $text\n";
}

相关问题