如何从.html页面中提取链接和标题?

2022-08-30 11:56:25

对于我的网站,我想添加一个新功能。

我希望用户能够上传他的书签备份文件(如果可能的话,从任何浏览器),这样我就可以将其上传到他们的个人资料,他们不必手动插入所有文件...

我唯一缺少的部分就是从上传的文件中提取标题和URL的部分。任何人都可以提供从哪里开始或从哪里阅读的线索吗?

使用搜索选项和(如何从原始HTML文件中提取数据?)这是我最相关的问题,它没有谈论它。

我真的不介意它是否使用jquery或php

谢谢。


答案 1

谢谢大家,我明白了!

最终代码:

$html = file_get_contents('bookmarks.html');
//Create a new DOM document
$dom = new DOMDocument;

//Parse the HTML. The @ is used to suppress any parsing errors
//that will be thrown if the $html string isn't valid XHTML.
@$dom->loadHTML($html);

//Get all links. You could also use any other tag name here,
//like 'img' or 'table', to extract other tags.
$links = $dom->getElementsByTagName('a');

//Iterate over the extracted links and display their URLs
foreach ($links as $link){
    //Extract and show the "href" attribute.
    echo $link->nodeValue;
    echo $link->getAttribute('href'), '<br>';
}

这将显示.html文件中所有链接的已分配文本和 href

再次,非常感谢。


答案 2

这可能就足够了:

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node)
{
  echo $node->nodeValue.': '.$node->getAttribute("href")."\n";
}

推荐