Php 如何从HTML页面中提取链接?
我正在尝试用php下载一个文件Php 如何从HTML页面中提取链接?,php,Php,我正在尝试用php下载一个文件 $file = file_get_contents($url); 如何在$url中下载文件中链接的内容…您需要手动或通过第三方插件解析生成的HTML字符串 您需要手动或通过第三方插件解析生成的HTML字符串 这需要解析HTML,这在PHP中是一个相当大的挑战。为了省去很多麻烦,请下载一个HTML解析库,如PHPQuery(http://code.google.com/p/phpquery/). 然后,您必须选择带有pq('a')的所有链接,通过它们循环获取它们的
$file = file_get_contents($url);
如何在$url中下载文件中链接的内容…您需要手动或通过第三方插件解析生成的HTML字符串
您需要手动或通过第三方插件解析生成的HTML字符串
这需要解析HTML,这在PHP中是一个相当大的挑战。为了省去很多麻烦,请下载一个HTML解析库,如PHPQuery(http://code.google.com/p/phpquery/). 然后,您必须选择带有
pq('a')
的所有链接,通过它们循环获取它们的href
属性值,对于每个链接,将其从相对值转换为绝对值,并在生成的URL上运行文件获取内容。希望这些指针能让您开始使用。这需要解析HTML,这在PHP中是一个相当大的挑战。为了省去很多麻烦,请下载一个HTML解析库,如PHPQuery(http://code.google.com/p/phpquery/). 然后,您必须选择带有pq('a')
的所有链接,通过它们循环获取它们的href
属性值,对于每个链接,将其从相对值转换为绝对值,并在生成的URL上运行文件获取内容。希望这些指针能让您开始使用。那么您想在给定文件中查找所有URL吗?雷格克斯来拯救。。。以及下面的一些示例代码,它们可以满足您的要求:
$file = file_get_contents($url);
if (!$file) return;
$file = addslashes($file);
//extract the hyperlinks from the file via regex
preg_match_all("/http:\/\/[A-Z0-9_\-\.\/\?\#\=\&]*/i", $file, $urlmatches);
//if there are any URLs to be found
if (count($urlmatches)) {
$urlmatches = $urlmatches[0];
//count number of URLs
$numberofmatches = count($matches);
echo "Found $numberofmatches URLs in $url\n";
//write all found URLs line by line
foreach($urlmatches as $urlmatch) {
echo "URL: $urlmatch...\n";
}
}
编辑:当我正确理解您的问题时,您现在想要下载找到的URL的内容。您可以在foreach
循环中为每个URL调用file\u get\u contents
,但您可能希望事先进行一些筛选(例如不下载图像等)。那么您想在给定的文件中查找所有URL吗?雷格克斯来拯救。。。以及下面的一些示例代码,它们可以满足您的要求:
$file = file_get_contents($url);
if (!$file) return;
$file = addslashes($file);
//extract the hyperlinks from the file via regex
preg_match_all("/http:\/\/[A-Z0-9_\-\.\/\?\#\=\&]*/i", $file, $urlmatches);
//if there are any URLs to be found
if (count($urlmatches)) {
$urlmatches = $urlmatches[0];
//count number of URLs
$numberofmatches = count($matches);
echo "Found $numberofmatches URLs in $url\n";
//write all found URLs line by line
foreach($urlmatches as $urlmatch) {
echo "URL: $urlmatch...\n";
}
}
编辑:当我正确理解您的问题时,您现在想要下载找到的URL的内容。您可以在foreach
循环中为每个URL调用file\u get\u contents
,但您可能希望事先进行一些筛选(如不要下载图像等)。通过调用file\u get\u contents下载链接,并将链接作为参数传递。通过调用file\u get\u contents可能会复制下载链接,将链接作为参数传递。的可能重复项