add a tag before img via php dom

时间:2015-06-15 14:23:43

标签: php dom

hi with this php dom code I change img attributes:

foreach ($imgs2 as $img) 
{   
    $img->setAttribute('src', $newsrc);
    $img->setAttribute('alt', 'hi');
    $img->setAttribute('width', $Size);
}

Is it possible to add an 'a' tag with href content of $newsrc with dom?

for exampple:

this is my current result:

<img alt="hi"  src = "pic1.png" />

I want something like this:

<a href="pic1.png"><img alt="hi"  src = "pic1.png" /></a>

1 个答案:

答案 0 :(得分:1)

// take example hytml
$str = '<html><img /></html>';

$dom = new DOMDocument();
$dom->loadHTML($str);

// Find img
$xpath = new DOMXPath($dom);
$imgs = $xpath->evaluate("//img");
$img = $imgs->item(0);

// Set (change) img attribute
$img->setAttribute('src', "src");
$img->setAttribute('alt', 'hi');
$img->setAttribute('width', "300");

// Create new a element
$element = new DOMElement('a');
// Insert it before img to save the point in dom
$element =  $img->parentNode->insertBefore($element, $img);
// set its attribute
$element->setAttribute('href', "src");
// Move img to be child of a
$element->appendChild($img);
echo $dom->saveHTML();

结果

<html><body>
<a href="src"><img src="src" alt="hi" width="300"></a>
</body></html>