0

Im using a PHP foreach loop to walk through an array of hyperlinks. if a condition is met, i want to change the href of the hyperlink. if not, the loop can continue. I am able to echo the current href using: echo $node->getAttribute( 'href' ); However i'm not able to change it using: $node->setAttribute('href', "https://www.website2.com");

Im missing something here, but i have been stuck on it for a while.

Full code:

  $dom = new DOMDocument;
  $dom->loadHTML($homepage);
  foreach ($dom->getElementsByTagName('a') as $node) {
    if ($node->getAttribute( 'href' ) == "https://www.website1.com"  ) {
      echo $node->getAttribute( 'href' );
      $node->setAttribute('href', "https://www.website2.com");
    }
  }
$html = $dom->saveHTML();

1 Answers1

0

Perhaps, if you are still having issues, the following will help.

<?php

    $strhtml="<!DOCTYPE html>
        <html lang='en'>
            <head>
                <meta charset='utf-8' />
                <title>Find and Replace</title>
            </head>
            <body>
                <h1>hmmmm</h1>
                <a href='https://www.example.com'>link #1</a>
                <a href='https://www.example.com'>link #2</a>
                <a href='https://www.example.com'>link #3</a>
            </body>
        </html>";
    
    $find='https://www.example.com';
    $repl='https://www.big-yellow-banana.com';
    
    
    $dom=new DOMDocument;
    $dom->loadHTML( $strhtml );
    
    
    $xp=new DOMXpath( $dom );
    $col=$xp->query( sprintf( '//a[ starts-with( @href, "%s" ) ]', $find ) );
    
    if( $col && $col->length > 0 ){
        foreach($col as $node){
            $node->setAttribute('href',str_replace($find,$repl,$node->getAttribute('href') ) );
        }
    }


    printf( 
        'Original:<textarea cols=100 rows=20>%s</textarea>
        <br />
        Modified:<textarea cols=100 rows=20>%s</textarea>
        <br />
        <br />
        Save this document to keep changes.... ie: $dom->saveHTML("/path/to/my-html-file.html");', $strhtml, $dom->saveHTML() );
?>

Which should yield:

Example output

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46