0

我正在使用以下代码使用 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 的样式表?

4

4 回答 4

2

如果您只想保持<link>元素不变,那么您可以使用 PHP 的 strip_tags()函数。

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

它接受一个定义允许标签的附加参数,因此您所要做的就是将唯一允许的标签设置为<link>标签。

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

这里的主要问题是您并不真正知道您将获得什么内容,并且尝试使用为该任务设计的工具以外的任何工具来解析 HTML 内容可能会让您头发灰白,紧张不安;)

参考 -

于 2012-08-27T09:56:45.413 回答
1

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

于 2012-08-27T09:56:15.407 回答
1

使用正则表达式:

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.'">';
  }
}
于 2012-08-27T09:57:37.810 回答
1

使用简单的 html dom 库

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>";
}
于 2012-08-27T10:00:17.970 回答