Change tag attribute value with PHP DOMDocument

2019-01-11 17:52发布

问题:

I want to change the value of the attribute of a tag with PHP DOMDocument.

For example, say we have this line of HTML:

<a href="http://foo.bar/">Click here</a>

I load the above code in PHP as follows:

$dom = new domDocument;
$dom->loadHTML('<a href="http://foo.bar/">Click here</a>');

I want to change the "href" value to "http://google.com/" using the DOMDocument extension of PHP. Is this possible?

Thanks for the help as always!

回答1:

$dom = new DOMDocument();
$dom->loadHTML('<a href="http://foo.bar/">Click here</a>');

foreach ($dom->getElementsByTagName('a') as $item) {

    $item->setAttribute('href', 'http://google.com/');
    echo $dom->saveHTML();
    exit;
}


回答2:

$dom = new domDocument;
$dom->loadHTML('<a href="http://foo.bar/">Click here</a>');

$elements = $dom->getElementsByTagName( 'a' );

if($elements instanceof DOMNodeList)
    foreach($elements as $domElement)
        $domElement->setAttribute('href', 'http://www.google.com/');