DATA; $doc = new DOMDocument('1.0', 'UTF-8'); $doc->strictErrorChecking = true; $doc->standalone = true; $doc->xmlStandalone = true; $doc->formatOutput = true; $doc->loadXML($data, LIBXML_NOWARNING | LIBXML_NOERROR); $sNode = $doc->getElementsByTagName("img"); $id = 0; foreach($sNode as $searchNode) { $searchNode->setAttribute('id', "img_$id"); $doc->importNode($searchNode); $id++; } $result = $doc->saveHTML(); echo $result;