Forgot password?
 Create new account
View 118|Reply 2

php自动关闭HTML标签

[Copy link]

3146

Threads

8493

Posts

610K

Credits

Credits
66158
QQ

Show all posts

hbghlyj Posted at 2024-3-5 21:40:18 |Read mode
  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. }
Copy the Code

測試:
  1. $html = '<div><p>This is some unclosed HTML';
  2. echo closeUnclosedTags($html);
Copy the Code

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

3146

Threads

8493

Posts

610K

Credits

Credits
66158
QQ

Show all posts

 Author| hbghlyj Posted at 2024-3-5 21:51:27
hbghlyj 发表于 2024-3-5 13:40
php自动关闭HTML标签?

測試:
上面的代码的innerHTML函数 参考了stackoverflow.com/questions/2087103/how-to-ge … innerhtml-of-domnode

3146

Threads

8493

Posts

610K

Credits

Credits
66158
QQ

Show all posts

 Author| hbghlyj Posted at 2024-3-5 21:55:13
再试一下 未关闭的html标签:
  1. $html = 'Unclosed iframe test: <iframe';
  2. echo closeUnclosedTags($html);
Copy the Code

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

手机版Mobile version|Leisure Math Forum

2025-4-20 22:04 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list