【问题标题】:How should parse with PHP (simple html dom parser) background images and other images of webpage?应该如何使用 PHP(简单的 html dom 解析器)背景图像和网页的其他图像进行解析?
【发布时间】:2011-03-14 07:53:43
【问题描述】:

PHP(simple html dom/etc..)背景和网页的其他图片应该如何解析?

案例1:内联css

<div id="id100" style="background:url(/mycar1.jpg)"></div>

案例2:html页面内的css

<div id="id100"></div>

<style type="text/css">
#id100{
background:url(/mycar1.jpg);
}
</style>

案例 3:单独的 css 文件

<div id="id100" style="background:url(/mycar1.jpg);"></div>

external.css

#id100{
background:url(/mycar1.jpg);
}

案例4:img标签内的图片

案例 4 的解决方案,正如他在 php simple html dom parser 中出现的那样:

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

请帮我解析案例 1,2,3。

如果有更多案例,请写出来,如果可以的话,请提供解决方案。

谢谢

【问题讨论】:

  • 使用 DOM 之类的库从 HTML 文件中获取内容之前已经回答了很多次(包括今天)。 SGML/XML 库不能处理外部 CSS 文件。另请注意,节点内容只是这些库的字符数据。如果要将内容解析为 CSS,则必须找到额外的解析器。

标签: php parsing html-parsing simple-html-dom


【解决方案1】:

对于案例 1:

// Create DOM from URL or file 
$html = file_get_html('http://www.google.com/');

// Get the style attribute for the item
$style = $html->getElementById("id100")->getAttribute('style');

// $style = background:url(/mycar1.jpg)
// You would now need to put it into a css parser or do some regular expression magic to get the values you need.

对于案例 2/3:

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Get the Style element
$style = $html->find('head',0)->find('style');

// $style now contains an array of style elements within the head. You will need to work out using attribute selectors what whether an element has a src attribute, if it does download the external css file and parse (using a css parser), if it doesnt then pass the innertext to the css parser.

【讨论】:

    【解决方案2】:

    要从页面中提取&lt;img&gt;,您可以尝试以下操作:

    $doc = new DOMDocument(); 
    $doc->loadHTML("<html><body>Foo<br><img src=\"bar.jpg\" title=\"Foo bar\" alt=\"alt\"></body></html>"); 
    $xml = simplexml_import_dom($doc);
    $images = $xml->xpath('//img'); 
    foreach ($images as $img) 
        echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title']; 
    

    有关详细信息,请参阅DOMDocument 的文档。

    【讨论】:

    • DOMElement 实现/允许 ArrayAccess?
    • 我已经为 img 标签编写了解决方案,我的答案仅适用于背景 css 图像
    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多