将 <li> 内文附加到 php url 抓取结果

Append <li> innertext to php url scraper results

我在一页上有 link 的列表:

<li><span><a href="https://site1.com">site1.com</a> : Description 1</span></li>
<li><span><a href="https://site2.com">site2.com</a> : Description 2</span></li>
<li><span><a href="https://site3.com">site3.com</a> : Description 3</span></li>
<li><span><a href="https://site4.com">site4.com</a> : Description 4</span></li>

我正在使用 php 从一个页面获取 links 并将它们显示在另一个页面上:

<?php
$urlContent = file_get_contents('https://www.example.com/');

$dom = new DOMDocument();
@$dom->loadHTML($urlContent);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for($i = 0; $i < $hrefs->length; $i++){
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    $url = filter_var($url, FILTER_SANITIZE_URL);
    if(!filter_var($url, FILTER_VALIDATE_URL) === false){
        echo '<a href="'.$url.'">'.$url.'</a><br />';
    }
}
?>

但是,我想弄清楚的是如何在 link 旁边包含说明。 这是我的许多尝试之一:

<?php
$urlContent = file_get_contents('https://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($urlContent);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a/li");
$li = document.getElementsByTagName("li");

for($i = 0; $i < $hrefs->length; $i++){
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    $url = filter_var($url, FILTER_SANITIZE_URL);
    if(!filter_var($url, FILTER_VALIDATE_URL) === false){
        echo '<a href="'.$url.'">'.$url.'</a> : '.$li.' <br />';
    }
}
?>

第一部分效果很好,但我尝试添加说明的所有操作都失败了。

这是一个根据当前标记的简单示例:

$dom = new DOMDocument();
@$dom->loadHTML($urlContent);
$xpath = new DOMXPath($dom);
$lis = $xpath->evaluate("/html/body/li");

foreach ($lis as $li) {
    $a = $xpath->evaluate("span/a", $li)->item(0);
    $url = $a->getAttribute('href');
    var_dump($url, $a->nextSibling->nodeValue);
}

这里的nextSibling是文本内容,跟在<a>标签后面,所以nextSibling->nodeValue就是" : Description",需要去掉空格和:,例如 trim.

工作fiddle