如何替换属性


How to replace the attribute

我想更改通过curl嵌入代码的页面的favicon。我试着在代码之前添加favicon,然而,favicon仍然被替换。

<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>

如何在没有favicon的情况下卷曲网站,或者使用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;
?>