【发布时间】:2021-01-06 08:30:53
【问题描述】:
我在一页上有一个链接列表:
<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 从一个页面获取链接并将它们显示在另一个页面上:
<?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 />';
}
}
?>
但是,我想弄清楚的是如何在链接旁边包含说明。 这是我的众多尝试之一:
<?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 />';
}
}
?>
第一部分效果很好,但我尝试添加描述的所有内容都失败了。
【问题讨论】:
-
我相信你的意思是 nodeValue -> php.net/manual/en/class.domnode.php#domnode.props.nodevalue
-
$xpath->evaluate("/html/body//a/li")没有什么意义,你没有li嵌套在a这里。 -
$hrefs->item($i)->nodeValue会得到 标签的内部文本
标签: php dom text html-lists