php - 使用 DOMXPath 和 DomDocument 检查网站是否使用有效的 AMP 结构
问题描述
我正在创建一个简单的函数,可以验证站点结构是否符合有效 AMP的标准。
为此,我必须检查 3 件事:
- 标签带有⚡
HTML
属性 - 如果存在带有属性的
style
标签amp-boilerplate
- 如果存在
script
src 等于的标签https://cdn.ampproject.org/v0.js
为此,我创建了以下代码:
$htmlContent = '<!doctype html>
<html ⚡>
<head>
<meta charset="utf-8">
<link rel="canonical" href="self.html" />
<meta name="viewport" content="width=device-width,minimum-scale=1">
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head>
<body>Hello, AMP world.2</body>
</html>';
function checkIfWebsiteIsUsingAMP($htmlContent) {
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($htmlContent);
libxml_use_internal_errors(false);
$xpath = new DOMXPath($dom);
$validOne = false;
$validTwo = false;
$validThree = false;
//Check if html tag has ⚡
if ($xpath->evaluate("//html ⚡")->length != 0) {
$validOne = true;
}
//Check if isset style amp-boilerplate
if ($xpath->evaluate("//style amp-boilerplate")->length != 0) {
$validTwo = true;
}
//Check if has script with src equal to 'https://cdn.ampproject.org/v0.js'
if ($xpath->evaluate("//script[@src='https://cdn.ampproject.org/v0.js']")->length != 0) {
$validThree = true;
}
return array('html_with_lightning' => $validOne, 'style_with_ampboilerplate' => $validTwo, 'script_with_src' => $validThree);
}
var_dump(checkIfWebsiteIsUsingAMP($htmlContent));
与检查标记中的(⚡) 和标记中的属性的最后分析(src
等于)分析似乎无法正常工作。'https://cdn.ampproject.org/v0.js'
lightning icon
html
amp-boilerplate
style
我该如何解决这个问题?
解决方案
尝试这个:
// Check if html tag has ⚡
if (strpos($htmlContent, '<html ⚡') !== false) {
$validOne = true;
}
// Check if isset style amp-boilerplate
if ($xpath->evaluate("//style[@amp-boilerplate]")->length != 0) {
$validTwo = true;
}
推荐阅读
- swift - 无法将 Swift 添加到 PATH Linux
- sql-server - 具有 NULL 值的 FIRST_VALUE 和 LAST_VALUE
- javascript - 当我更改不相关的状态时,为什么我的所有组件都会重新渲染?
- node.js - 从 CLI 命令执行 webpack 时出现“Module not found”错误,注册在自己库的“/bin”中
- python - 在 python 中修复排行榜
- wordpress - 如何禁用 woocommerce 中的复选框字段?
- batch-file - 为什么大部分输出没有被重定向到文件?
- python - How to plot months (in order) using Seaborn bar plot?
- node.js - npm 包与 webpack 捆绑不正确
- php - 上传大于 300Kb 的大尺寸图像时 cloudfare 超时问题(大约)