You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DOMDocument移除带@的HTML属性:@click事件监听器丢失问题咨询

解决DOMDocument移除带@前缀HTML属性的问题

当用PHP的DOMDocument处理含框架专属属性(如@click)的HTML时,这类带@前缀的非标准属性会被自动过滤,示例代码如下:

$html = '<button @click="test()">ÁÈ</button>';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $html);
dump($dom);

// 预期结果 - <button @click="test()">ÁÈ</button>
// 实际结果  - <button>ÁÈ</button>

原因

DOMDocument依赖libxml库,默认遵循HTML标准规范,@click这类带@前缀的属性不属于标准HTML属性,因此会被libxml自动清理。

解决方案

方案一:使用loadXML替代loadHTML

XML允许自定义属性,切换为loadXML方法可以保留所有自定义属性,无需修改原始HTML:

$html = '<button @click="test()">ÁÈ</button>';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
// 用loadXML加载内容,LIBXML_NOERROR忽略XML格式警告
$dom->loadXML($html, LIBXML_NOERROR);
// 输出处理后的内容
echo $dom->saveXML($dom->documentElement);

注意:使用loadXML要求HTML结构符合XML规范(比如标签必须正确嵌套、自闭合标签需加/),如果处理的是不规范的HTML,可能需要先做格式调整。

方案二:临时替换@前缀(兼容不规范HTML)

如果必须用loadHTML处理不规范HTML,可以先把@前缀替换为合法的临时标识,处理完成后再替换回@:

$html = '<button @click="test()">ÁÈ</button>';
// 将@替换为不会冲突的临时字符串
$tempHtml = str_replace('@', 'temp-attr-prefix-', $html);

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $tempHtml);

// 处理完成后,把临时标识替换回@
$result = str_replace('temp-attr-prefix-', '@', $dom->saveHTML());
echo $result;

注意:选择临时标识时要确保不会和HTML中已有的内容重复,避免替换出错。

内容的提问来源于stack exchange,提问作者André Rodrigues

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 22:17:04