0

我是 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;
4

1 回答 1

2

使用 dom 的 simplexml 是否可行?

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;
于 2013-01-10T13:20:09.967 回答