找回密码
 快速注册
搜索
查看: 24|回复: 2

php自动关闭HTML标签

[复制链接]

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

hbghlyj 发表于 2024-3-5 21:40 |阅读模式
  1. <?php
  2. function innerHTML($node) {
  3.     return implode(array_map([$node->ownerDocument,"saveHTML"],
  4.                              iterator_to_array($node->childNodes)));
  5. }
  6. function closeUnclosedTags($html) {
  7.     $dom = new DOMDocument();
  8.     @$dom->loadHTML($html);
  9.     // Get the body element
  10.     $body = $dom->getElementsByTagName('body')->item(0);
  11.     // Save only the HTML content of the body element
  12.     return innerHTML($body);
  13. }
复制代码

測試:
  1. $html = '<div><p>This is some unclosed HTML';
  2. echo closeUnclosedTags($html);
复制代码

輸出:
<div><p>This is some unclosed HTML</p></div>

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

 楼主| hbghlyj 发表于 2024-3-5 21:51
hbghlyj 发表于 2024-3-5 13:40
php自动关闭HTML标签?

測試:

上面的代码的innerHTML函数 参考了stackoverflow.com/questions/2087103/how-to-get-innerhtml-of-domnode

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

 楼主| hbghlyj 发表于 2024-3-5 21:55
再试一下 未关闭的html标签:
  1. $html = 'Unclosed iframe test: <iframe';
  2. echo closeUnclosedTags($html);
复制代码

<p>Unclosed iframe test: <iframe></iframe></p>
看起来成功了

手机版|悠闲数学娱乐论坛(第3版)

GMT+8, 2025-3-4 15:25

Powered by Discuz!

× 快速回复 返回顶部 返回列表