【问题标题】:PHP cURL to return remote page stylesheetsPHP cURL 返回远程页面样式表
【发布时间】:2012-08-27 09:50:11
【问题描述】:

我正在使用以下代码使用 PHP cURL 获取远程内容

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

此代码返回全部内容但我只想按以下格式打印所有样式表。

<link rel="stylesheet" href="http://www.example.com/css/style1.css">
<link rel="stylesheet" href="http://www.example.com/css/style2.css">

如何使用 str.replace() 过滤内容以仅获取带有 cURL 的样式表?

【问题讨论】:

    标签: php string curl


    【解决方案1】:

    如果您希望保持&lt;link&gt; 元素不变,则可以使用PHP 的strip_tags() 函数。

    strip_tags — 从字符串中去除 HTML 和 PHP 标记

    它接受一个定义允许标签的附加参数,因此您只需将唯一允许的标签设置为&lt;link&gt; 标签。

    $output = curl_exec($ch);
    $linksOnly = strip_tags($ouput,'link');
    

    这里的主要问题是您并不真正知道您将获得什么内容,并且尝试使用专为该任务设计的工具以外的任何工具解析 HTML 内容可能会给您留下grey hair and a nervious twitch ;)

    参考资料 -

    【讨论】:

      【解决方案2】:

      使用simple html dom library

      include('simple_html_dom.php');
      
      // get DOM from URL or file
      $html = file_get_html('http://www.example.com/');
      // or your can get $html string through your curl request and say
      // $html = str_get_html($html);
      
      // find all "link"
      foreach($html->find('link') as $e) {
          if($e->type="text/css" && strpos($e->href, ":/") !=== false) // you don't want relative css hrefs. right?
          echo $e->href."<br>";
      }
      

      【讨论】:

      • 知道simple_html_dom.php 来自哪里可能会很有趣。
      【解决方案3】:

      更好的方法是使用 PHP DOM 解析 HTML 树并检索所需的节点 - 在您的情况下为 &lt;link&gt; - 并适当地过滤它们。

      【讨论】:

        【解决方案4】:

        使用正则表达式:

        preg_match_all('/rel="stylesheet" href="(.*)">/', $output, $matches);
        
        if (isset($matches[1]) && count($matches[1]))
        {
          foreach ($matches as $value)
          {
            echo '<link rel="stylesheet" href="'.$value.'">';
          }
        }
        

        【讨论】:

        • 如果我的网站有&lt;link type="text/css" rel="stylesheet" media="screen" href="/foo/" /&gt;怎么办?我认为正则表达式有一些注意事项。
        • 好吧,我不能同意,但 OP 没有提供任何输出示例。 href 也可以在rel 之前。
        • 这就是为什么人们说你不应该使用正则表达式来解析 HTML,我认为 ^_^ 嗯,它确实回答了这个问题,所以 +1。
        猜你喜欢
        • 2012-08-21
        • 2020-08-16
        • 1970-01-01
        • 1970-01-01
        • 2020-10-06
        • 1970-01-01
        • 2012-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多