PHP作为众多开发语言中最快速的开发语言之一,在写后端服务中有着一定的优势,下边随源码码网小编一起来看看PHP实现获取网站TDK内容的API接口。

<?php
header('Content-Type: application/json');
// 获取URL参数
$url = $_GET['url'] ?? null;
if (!$url) {
http_response_code(400);
echo json_encode(['error' => 'URL parameter is required']);
exit;
}
// 获取网页内容
$html = @file_get_contents($url);
if (!$html) {
http_response_code(500);
echo json_encode(['error' => 'Failed to fetch the URL']);
exit;
}
// 解析TDK
$dom = new DOMDocument();
@$dom->loadHTML($html);
$title = $dom->getElementsByTagName('title')->item(0)->nodeValue ?? null;
$description = null;
$keywords = null;
$metaTags = $dom->getElementsByTagName('meta');
foreach ($metaTags as $tag) {
if ($tag->getAttribute('name') === 'description') {
$description = $tag->getAttribute('content');
}
if ($tag->getAttribute('name') === 'keywords') {
$keywords = $tag->getAttribute('content');
}
}
// 返回结果
echo json_encode([
'title' => $title,
'description' => $description,
'keywords' => $keywords
]);将代码保存为 tdk.php,然后将其部署到一个支持PHP的服务器(如Apache或Nginx)。
访问以下URL来测试API:
http://your-server/tdk.php?url=https://example.com




B2C电商系统商城源码支持pC+小程序+公众号+H5可打包App源...
原生开发淘宝客App,Android+ios独立开发,全开源支持二...
知识付费系统在线教育平台源码+题库系统源码,PC+公众号商业授权...
B2C单商户电商系统源码部署小程序+公众号+H5+App源码...
教育知识付费系统源码带题库功能商业授权公众号+H5源码...