【问题标题】:How to get contents of page stylesheets using php dom?如何使用 php dom 获取页面样式表的内容?
【发布时间】:2012-12-24 21:16:59
【问题描述】:

我是 php 新手,谁能建议如何使用php dom 获取页面样式表的内容,以便它们出现在页面上?

假设在页面头部是:

<link rel="stylesheet" href="resources/css/reset.css" type="text/css" media="screen"/>
<link rel="stylesheet" href="resources/css/style.css" type="text/css" media="screen"/>
<link rel="stylesheet" href="resources/css/invalid.css" type="text/css" media="screen"/>
<link rel="stylesheet" href="resources/css/blue.css" type="text/css" media="screen"/>

如何获取这些样式表的内容?

更新:

$url = 'http://wordpress.stackexchange.com/questions/60792/replace-image-attributes-for-lazyload-plugin-data-src';
$html = file_get_contents($url);

$xml = new SimpleXMLElement($html);
/* Search for <link rel=stylesheet> */
$result = $xml->xpath('link[@rel="stylesheet"]');

foreach($result as $node) { 
    echo $node->{'@attributes'}->href . "\n";
}
exit;

【问题讨论】:

  • @k102:不是我的问题的答案。无论如何,我想将它们组合并压缩成一个。我知道有解决方案,但我正在开发一个自定义库,所以我需要这样做。
  • 谢谢,队长,这不是答案,而是评论:) 我认为还有另一种方法可以完成您的任务...

标签: php regex parsing dom


【解决方案1】:

是否可以使用simplexml insted of dom?

http://php.net/manual/en/simplexmlelement.xpath.php

<?php

$url = 'http://wordpress.stackexchange.com/questions/60792/replace-image-attributes-for-lazyload-plugin-data-src';
$url_parts = parse_url($url);

$html = file_get_contents($url);

$doc = new DOMDocument();
// A corrupt HTML string
$doc->loadHTML($html);

$xml = simplexml_import_dom($doc);

/* Search for <link rel=stylesheet> */
$result = $xml->xpath('//link[@rel="stylesheet"]');

foreach($result as $node) { 
    $link = $node->attributes()->href;

    if (substr($link, 0, 4) == 'http') {
        // nothing to do
    } else if (substr($link, 0, 1) == '/') {
        $link = $url_parts['scheme'] . '://' . $link;
    } else {
        $link = $url_parts['scheme'] . '://' . dirname($url_parts['scheme']) . '/' . $link;
    }

    echo '--> ' . $link . "\n";
}
exit;

【讨论】:

  • arning: SimpleXMLElement::__construct(): Entity: line 41: parser error : EntityRef: expecting ';'
  • Warning: SimpleXMLElement::__construct(): &amp;quot;:true,&amp;quot;enableUserHovercards&amp;quot;:true,&amp;quot;site&amp;quot;:{&amp;quot;name&amp;quot;:&amp;quot;WordPress&amp;quot;,&amp;quot;description&amp;quot;:&amp;quot;Q&amp;amp;A
  • Warning: SimpleXMLElement::__construct(): ^
  • 它似乎是无效的 html,改变了我的答案,现在它应该可以工作了
猜你喜欢
  • 1970-01-01
  • 2021-05-11
  • 2011-09-12
  • 2015-12-16
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
相关资源
最近更新 更多