【发布时间】:2020-05-02 01:04:27
【问题描述】:
我正在尝试编写一个 html 文件,其中有一个 URL 链接,类似的名称是链接本身的标题。
为此,我遵循以下帖子的第二个答案中提出的答案:How can I get the title of a webpage given the url (an external url) using JQuery/JS
<!DOCTYPE html>
<html>
<head>
<script>
function getTitle(externalUrl){
var proxyurl = "./get_external_content.php?url=" + externalUrl;
$.ajax({
url: proxyurl,
async: true,
success: function(response) {
alert(response);
},
error: function(e) {
alert("error! " + e);
}
});
}
</script>
</head>
<body>
<!-- Link to news -->
<a href="https://www.corriere.it/economia/tasse/cards/irpef-2020-come-cambiano-scaglioni-studio-riforma-aliquote/mosse-governo_principale.shtml">Notizia Corriere</a>.
getTitle("https://www.corriere.it/economia/tasse/cards/irpef-2020-come-cambiano-scaglioni-studio-riforma-aliquote/mosse-governo_principale.shtml")
PHP 文件是这样的:
<?php
function file_get_contents_curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = $_REQUEST["url"];
$html = file_get_contents_curl($url);
preg_match('/<title>(.+)<\/title>/',$html,$matches);
$title = $matches[1];
echo json_encode(array("url" => $url, "title" => $title));
我不得不说我不确定我是否正确调用了 .php 函数,对于 getTitle 函数也是如此。 对你们中的许多人来说,这可能是一个基本问题,但我没有 html/php 经验,我无法解决这个问题。您能否引导我找到解决此问题的正确方法?
【问题讨论】:
-
你的 PHP 脚本的内容是什么?加载您的页面,按 F12,转到 Network 选项卡并监控请求;查找任何非 200 代码。
-
@user8555937 好点!我刚刚添加了它:)
标签: javascript php html url title