【问题标题】:Get Webpage Title from URL in PHP not working从 PHP 中的 URL 获取网页标题不起作用
【发布时间】:2020-03-26 16:44:36
【问题描述】:

我正在尝试通过 post 和 scrape 该 HTML 页面的标题接收某个 url。然后,我会将页面的标题存储到我的 MySQL 数据库中。

在将这个功能应用到我的实际在线服务器之前,我在本地服务器上测试了 page_title 函数(它是读取给定 URL 的 HTML 页面标题的自定义函数),它运行良好。这是我在本地服务器上使用的代码。

<?php 
   $link = $_POST['link'];
   function page_title($url) {
   $fp = file_get_contents($url);
   if (!$fp)
       return null;

   $res = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches);
   if (!$res)
       return null;

   // Clean up title: remove EOL's and excessive whitespace.
   $title = preg_replace('/\s+/', ' ', $title_matches[1]);
   $title = trim($title);
   return $title;
  }

  $title= page_title($link);
  echo $title;   ?>

但是,当我在在线服务器上使用完全相同的代码将数据实际推送到 MYSQL 数据库时,该函数似乎返回 nothing 而是一个空字符串。结果,每当我检查我的 php myadmin 时,“标题”列上都没有出现任何内容。谁能告诉我我能做些什么来完成这项工作?谢谢!

【问题讨论】:

  • 您是否要抓取启用 SSL 的网站?

标签: php mysql post html-parsing file-get-contents


【解决方案1】:

我建议通过这样做来简化它(删除 cmets,因为它信息太多):

<?PHP

# Get the HTML from a web page
$html = file_get_contents("http://whatever.url");

# Get all HTML titles in to an array (this is your own code)
$res = preg_match("/<title>(.*)<\/title>/siU", $html, $titleArray);

# Get the first array entry - and an empty string if the tag does not exists
$title = isset($titleArray[0]) ? $titleArray[0] : "";

# Remove HTML tags from the string
$title = strip_tags($title);

# Show the title - convert HTML tags just to show it does not have any
echo "[". htmlentities($title) ."]";

# Save it to your database ...

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多