【问题标题】:PHP change href when condition is met满足条件时PHP更改href
【发布时间】:2021-06-11 14:21:56
【问题描述】:

我使用 PHP foreach 循环遍历一组超链接。 如果满足条件,我想更改超链接的href。如果没有,循环可以继续。 我可以使用 echo $node->getAttribute( 'href' ); 回显当前的 href 但是我无法使用以下方法更改它: $node->setAttribute('href', "https://www.website2.com");

我在这里遗漏了一些东西,但我已经坚持了一段时间。

完整代码:

  $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();

【问题讨论】:

  • 您是否真的在脚本末尾保存了文档?
  • 不,我不这么认为
  • 如果您不保存,更改将不会是永久性的。这取决于您如何使用上述内容。
  • 我应该添加什么来保存文档?也许就这么简单:)
  • $html = $dom->saveHTML();

标签: php domdocument getelementsbytagname setattribute getattribute


【解决方案1】:

也许,如果您仍然遇到问题,以下方法会有所帮助。

<?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() );
?>

应该产生的结果:

【讨论】:

  • 非常感谢您的回复,真的很有帮助!我会尝试你的建议,如果它有效,我会告诉你!
  • 非常感谢您的分享:)
  • 很高兴能为您提供一些帮助。
猜你喜欢
  • 2012-09-15
  • 1970-01-01
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 2023-01-12
  • 2013-05-28
相关资源
最近更新 更多