Close or Fix a broken img tag using PHP

故事扮演 提交于 2019-12-23 04:45:08

问题


I'm having troubles fixing a 'broken' html string, using PHP

I'm facing the common problem of using substr on an html string, which results in broken tags.

I've managed to fix all the broken tags, except the image one, as the tag itself is not complete, it's not even an opening tag,

For example, Suppose you have a string:

<div><img alt="foo" title="bar" 

I'd really want to to add a > to close this, and my other scripts know how to close the div automatically.

Does anyone have any ideas on how to catch broken <img> tags and automatically fix them?

I've seen many solutions including DOMdocument, tidy and HTMLpurifier, but they don't seem to fix this specific problem.

Any help would be appreciated.


回答1:


Yes you can repair tags using DOMDocument. (Based on example):

$html = '<div><img alt="foo" title="bar"';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

$out = '';
foreach ($dom->getElementsByTagName('body')->item(0)->childNodes as $child) {
    $out .= $dom->saveXML($child);
}
echo htmlentities($out);

  • Fiddle demo


来源:https://stackoverflow.com/questions/25846098/close-or-fix-a-broken-img-tag-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!