源码教程 2025年06月7日
0 收藏 0 点赞 538 浏览 1285 个字
摘要 :

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

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

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

微信扫一扫

支付宝扫一扫

版权: 转载请注明出处:https://www.zuozi.net/1915.html

管理员

相关推荐
2025-07-05

对于一些使用WordPress进行外贸建站的商家来说,大部分人会通过在WordPress中添加JS代码和CSS样式表…

700
2025-07-05

当商家遇到WordPress独立站改版或者域名到期等问题时,不免会涉及到WordPress域名的更改,那么这一…

714
2025-07-05

用户在使用WooCommerce进行跨境电商独立站搭建工作时,有可能会借助WooCommerce短代码实现更加醒目…

305
2025-07-05

随着外贸建站行业的不断深入发展,WordPress的多语言功能也显得越来越重要,一个具有多语言的独立站…

1,038
2025-07-05

WooCommerce作为WordPress外贸建站生态的一部分,WooCommerce运费设置是商家在建站过程中不可忽视的…

834
2025-07-05

在外贸建站的过程中,有些商家会选择使用WordPress幻灯片为网站页面增加一定的动感和可观性,进而提…

721
发表评论
暂无评论

还没有评论呢,快来抢沙发~

助力内容变现

将您的收入提升到一个新的水平

点击联系客服

在线时间:08:00-23:00

客服QQ

122325244

客服电话

400-888-8888

客服邮箱

122325244@qq.com

扫描二维码

关注微信客服号