场景是我从MySQL数据库中获取记录。此记录数据采用HTML格式,因此我想从此HTML数据记录中删除少量标记。为此我也写了一个函数。但我不明白为什么控制不会进入foreach。供你参考我在下面给出了函数的某些部分:
function clear_question_data($html){
$dom = new DOMDocument();
$dom->loadHTML($html);
foreach($dom->getElementsByTagName('img') as $image)
{ echo "Inside Foreach"; die;
$image->removeAttribute('alt');
$image->removeAttribute('xmlns');
$image->removeAttribute('title');
}
echo "Out of Foreach"; die;
$txt=$dom->saveHTML();
$dom->loadHTML($txt);
foreach($dom->getElementsByTagName('img') as $image)
{
$srcval=$image->getAttribute('src');
$srcval = htmlspecialchars_decode($srcval);
$srcval = str_replace(' ', ' ', $srcval);
if(strpos($srcval,"%5C%22")==0)
{
$srcval = str_replace("%5C%22", "", $srcval);
$srcval = str_replace(".png%5C%22", ".png", $srcval);
}
if(strpos($srcval,"../../..")==0)
{
$srcval = str_replace("../../..", "", $srcval);
}
if(strpos($srcval,"../..")==0)
{
$srcval = str_replace("../..", "", $srcval);
}
if(strpos($srcval,"/ckeditor_3.6.1//plugins")==0)
{
$srcval = str_replace("/ckeditor_3.6.1//", EPN_SITE_URL."ckeditor_3.6.1/", $srcval);
}
$srcval = str_replace(".png/\"", ".png", $srcval);
$srcval = str_replace("�", "-", $srcval);
$image->setAttribute('src',$srcval);
}
$final_data=$dom->saveHTML();
return $final_data;
}
样本输入数据(即$html
)如下:
Glucose when hetaed with CH<sub>3</sub>OH in presence of dry HCl gas gives<img align=\"middle\" alt=\"«math xmlns=¨http://www.w3.org/1998/Math/MathML¨»«mi»§#945;«/mi»«/math»\" class=\"Wirisformula\" src=\"/ckeditor_3.6.1//plugins/ckeditor_wiris/integration/showimage.php?formula=dedbf6a559a928eeeaee82c4b1bf40d3.png\" title=\"Double click to edit\"> and <img align=\"middle\" alt=\"«math xmlns=¨http://www.w3.org/1998/Math/MathML¨»«mi»§#946;«/mi»«/math»\" class=\"Wirisformula\" src=\"/ckeditor_3.6.1//plugins/ckeditor_wiris/integration/showimage.php?formula=2c5cf4a4494a03be06d6c32308a225ba.png\" title=\"Double click to edit\">-methyl glycosides because it contains.<br>
每当我尝试调试此函数时,我都会收到一条消息“Out of Foreach”而不是“Inside Foreach”。我不知道为什么会这样。有人可以帮我这方面吗?任何形式的帮助将受到高度赞赏。如果你有更好的方法来实现这个结果,那么欢迎它。
答案 0 :(得分:0)
虽然你说加载没有问题,但请尝试加载它,因为代码格式不正确:
$dom = new DOMDocument;
$dom->strictErrorChecking = FALSE;
$dom->loadHTML($html);