PHP作为众多开发语言中最快速的开发语言之一,在写后端服务中有着一定的优势,下边随源码码网小编一起来看看PHP实现获取网站TDK内容的API接口。 <?php header('……
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
还没有评论呢,快来抢沙发~