php DomDocument adds extra tags

后端 未结 5 709
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 03:09

I\'m trying to parse a document and get all the image tags and change the source for something different.


    $domDocument = new DOMDocument();

    $domDo         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 03:58

    You just need to add 2 flags to the loadHTML() method: LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD. I.e.

    $domDocument->loadHTML($text, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
    

    See IDEONE demo:

    $text = '

    Hi, this is a test, here is an image Because I like Beer!

    '; $domDocument = new DOMDocument; $domDocument->loadHTML($text, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD); $imageNodeList = $domDocument->getElementsByTagName('img'); foreach ($imageNodeList as $Image) { $Image->setAttribute('src', 'lalala'); $domDocument->saveHTML($Image); } $text = $domDocument->saveHTML(); echo $text;

    Output:

    Hi, this is a test, here is an image Because I like Beer!

提交回复
热议问题