如何从 php 中的 URL 检索网站标题?
Posted
技术标签:
【中文标题】如何从 php 中的 URL 检索网站标题?【英文标题】:How to retrieve site title from URL in php? 【发布时间】:2021-08-31 06:47:01 【问题描述】:<form method="POST" action=" route('storeCompany') ">
<label> __('Website URL') </label>
<input type="text" name="url" value=" old('url') " class="form-control" required="required">
<label> __('Site Title') </label>
<input type="text" name="name" value=" old('name') " class="form-control" required="required">
<input type="submit" name="sbNewReviewItem" class="btn btn-block btn-primary" value=" __('Submit') ">
</form>
这是我的表单,我希望根据网站 URL 自动完成网站标题字段(它也必须是可编辑的)。
示例:我输入https://***.com/
作为网站标题,然后网站标题必须在网站标题字段中显示Stack Overflow - Where Developers Learn, Share, &amp; Build Careers
(网站标题)。如果您知道执行此操作的方法,请告诉我。谢谢!
【问题讨论】:
希望下面的答案对你有用。 【参考方案1】:DEMO 对于这个函数,你可以使用 url 获取标题名称。
对于这个功能,您可以使用 url 获取标题名称
<?php
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;
print page_title("https://***.com");
?>
输出:Stack Overflow - 开发人员学习、分享和建立职业生涯的地方
LARAVEL 代码
HTML 代码
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<form method="POST" action=" route('storeCompany') " id="websiteForm">
csrf_field()
<label> __('Website URL') </label>
<input type="text" name="url" value=" old('url') " class="form-control url" required="required">
<label> __('Site Title') </label>
<input type="text" name="title" value=" old('name') " class="form-control title"/>
<input type="submit" name="sbNewReviewItem" class="btn btn-block btn-primary clssubmit" value=" __('Submit') ">
</form>
路线代码
Route::post('changestatus', ['as' => 'changestatus', 'uses' => 'YourControllerName@changestatus']);
Route::post('checktitle', ['as' => 'checktitle', 'uses' => 'YourControllerName@checktitle']);
控制器代码
public function checktitle(Request $request)
try
$data = self::page_title($request->val);
$arr = array("status" => 200, "msg" => 'success',"result" => $data);
catch (\Illuminate\Database\QueryException $ex)
$msg = 'Something went wrong.';
if (isset($ex->errorInfo[2]))
$msg = $ex->errorInfo[2];
$arr = array("status" => 400, "msg" => $msg, "result" => array());
catch (Exception $ex)
$msg = 'Something went wrong.';
if (isset($ex->errorInfo[2]))
$msg = $ex->errorInfo[2];
$arr = array("status" => 400, "msg" => $msg, "result" => array());
return \Response::json($arr);
private 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;
Ajax 代码
$('body').on('keyup', '.url', function (e)
var val= $( ".url" ).val( );
e.preventDefault();
$.ajax(
url: " route('checktitle')", // write your route path
headers:
'X-CSRF-TOKEN': ' csrf_token() '
,
data: val : val,
type: 'POST',
beforeSend: function ()
$('.clssubmit').prop("disabled", true);
,
success: function (data)
if (data.status == 400)
$('.submitspinner').html('');
toastr.error(data.msg)
if (data.status == 200)
$('.clssubmit').prop("disabled", false);
$( ".title" ).val(data.result);
toastr.success(data.msg)
,
);
);
【讨论】:
希望这个答案对你有用!! @Codenooober【参考方案2】:您可以使用Javascript通过document.title
获取<title>
标签的内容。然后,您可以将其推送到对应的<label>
标签。
【讨论】:
【参考方案3】:你会在这里得到答案 [https://www.php.net/manual/en/function.get-meta-tags.php][1]
`$tags = get_meta_tags('https://***.com/');
print_r($tags);`
【讨论】:
【参考方案4】:刀片模板
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<form method="POST" action=" route('storeCompany') " id="websiteForm">
@csrf
<label> __('Website URL') </label>
<input type="text" name="url" value=" old('url') " class="form-control" required="required">
<label> __('Site Title') </label>
<input type="text" name="title" value=" old('name') " class="form-control name"/>
<input type="submit" name="sbNewReviewItem" class="btn btn-block btn-primary" value=" __('Submit') ">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js" integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
$("#websiteForm").submit(function(e)
e.preventDefault();
var bodyFormData = new FormData(this);
var url=$(this).attr('action');
axios.post(url,bodyFormData).then(function (response)
console.log(response.data);
$('input[name="title"]').val(response.data.title)
return false;
).catch(function (error)
);
);
</script>
</body>
</html>
在 Laravel 方面
if(request()->isMethod('POST'))
$html = file_get_contents(request()->url);
$xml = new DOMDocument();
libxml_use_internal_errors(true);
$xml->validateOnParse = true;
$xml->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
return [
'title'=>$xml->getElementsByTagName('title')->item('0')->nodeValue,
];
【讨论】:
以上是关于如何从 php 中的 URL 检索网站标题?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 SLUG php mysql 从 url 检索数据
如何从 WordPress 网站 URL 中删除 index.php [重复]