如何替换属性

How to replace the attribute

我想通过curl更改嵌入代码的页面的图标。我试图在代码之前添加网站图标,但是,网站图标仍然被替换。

<html>
<link rel="shortcut icon"  type="image/x-icon"  href="./favicon.ico"/>
<?php
  $ch = curl_init();
  $options = array(CURLOPT_URL => 'nicovideo.jp',
    CURLOPT_HEADER => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true
    );
   curl_setopt_array($ch, $options);
   $output = curl_exec($ch);
   curl_close($ch);
   echo $output;
 ?>
</html>

如何在没有网站图标的情况下卷曲网站或使用 DOM 更改有关图标 src/href 的所有代码?

从远程站点获取源代码并使用 DOMDocument 操作内容非常简单。

<?php
    $ch = curl_init();
    $options = array(
        CURLOPT_URL             => 'nicovideo.jp',
        CURLOPT_HEADER          => false,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_FOLLOWLOCATION  => true
    );
    curl_setopt_array($ch, $options);
    $output = curl_exec($ch);
    curl_close($ch);

    /* Create DOM object */
    libxml_use_internal_errors( true );
    $dom = new DOMDocument('1.0','utf-8');
    $dom->validateOnParse=false;
    $dom->standalone=true;
    $dom->strictErrorChecking=false;
    $dom->recover=true;
    $dom->loadHTML( $output );
    $parse_errs=serialize( libxml_get_last_error() );
    libxml_clear_errors();

    /* Get all the nodes you are interested in */
    $col=$dom->getElementsByTagName('link');
    foreach( $col as $node ){

        /* loop through nodes to find those of interest */
        if( $node->hasAttribute('rel') && $node->getAttribute('rel')=='shortcut icon' ){

            /* set the new attribute value */
            $node->setAttribute( 'href', 'https://'.$_SERVER['SERVER_NAME'].'/favicon.ico' );
        }
    }
    /* show the final result */
    echo $dom->saveHTML();
    $dom=null;
?>