【问题标题】:How to replace the attribute如何替换属性
【发布时间】:2015-10-30 15:36:17
【问题描述】:

我想通过 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>

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

【问题讨论】:

  • 在 StackOverflow 上发布您尝试过的现有代码是一种很好的做法,并附上关于它为什么不起作用的具体问题。
  • 我认为您想要完成的只是使用不同的 favicon 镜像 nicovideo 是否正确?
  • 类似,nicovideo 只是一个示例。

标签: javascript php html curl attributes


【解决方案1】:

从远程站点获取源并使用 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;
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-25
    • 2016-12-06
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2018-05-06
    • 2012-09-11
    相关资源
    最近更新 更多