Forgot password
 Register account
View 238|Reply 2

php自动关闭HTML标签

[Copy link]

3207

Threads

7846

Posts

51

Reputation

Show all posts

hbghlyj posted 2024-3-5 21:40 |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>

3207

Threads

7846

Posts

51

Reputation

Show all posts

original poster hbghlyj posted 2024-3-5 21:51
hbghlyj 发表于 2024-3-5 13:40
php自动关闭HTML标签?

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

3207

Threads

7846

Posts

51

Reputation

Show all posts

original poster hbghlyj posted 2024-3-5 21:55
再试一下 未关闭的html标签:
  1. $html = 'Unclosed iframe test: <iframe';
  2. echo closeUnclosedTags($html);
Copy the Code
<p>Unclosed iframe test: <iframe></iframe></p>
看起来成功了

Quick Reply

Advanced Mode
B Color Image Link Quote Code Smilies
You have to log in before you can reply Login | Register account

$\LaTeX$ formula tutorial

Mobile version

2025-7-12 12:55 GMT+8

Powered by Discuz!

Processed in 0.063024 seconds, 36 queries