我想显示给定网址中的所有链接。我通过搜索找到了它。但它也显示"title"
"a"
标记的属性。我只想要“href”的属性
<?php
$link = file_get_contents('http://example.com');
$dom = new DOMDocument;
@$dom->loadHTML($link);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link){
echo $link->nodeValue;
echo $link->getAttribute('href'), '<br>';
}
?>
任何人都可以帮我这样做吗?提前致谢
答案 0 :(得分:1)
<a>value</a>
的值与echo $link->nodeValue;
一起删除该代码并解决了问题。
但是,此处并未真正处理网站的内部链接。 也许添加这样的东西:
$url = 'http://example.com';
... # other code.
foreach($links as $link){
if($link[0] == '/'){ #link is a string, [0] refers to the first character.
echo $url, $link->getAttribute('href');
} else {
echo $link->getAttribute('href'), "\n";
}
}
另一件事,抑制错误(@
)不是要走的路。找到另一种无误的分辨率。
答案 1 :(得分:0)
我建议使用Symfony2框架和Goutte的组合。
Symfony2:https://symfony.com/
Goutte:https://github.com/FriendsOfPHP/Goutte
你要创建一个新实例:
use Goutte\Client;
$client = new Client();
然后请求页面:
// Go to the symfony.com website
$crawler = $client->request('GET', 'http://www.symfony.com/blog/');
然后尝试得到你需要的东西:
$links = $crawler->filter('a[href]');
foreach ($links as $link) {
echo '<a href="$link">$link</a><br>';
}