Change tag attribute value with PHP DOMDocument

后端 未结 2 714
無奈伤痛
無奈伤痛 2020-11-30 09:53

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

For example, say we have this line of HTML:



        
相关标签:
2条回答
  • 2020-11-30 10:12
    $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/');
    
    0 讨论(0)
  • 2020-11-30 10:23
    $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;
    }
    
    0 讨论(0)
提交回复
热议问题