简单的html dom从样式css获取背景图像URL

时间:2018-01-20 19:40:24

标签: php css

我正在尝试使用简单的html dom从hd-banner-image css代码获取图片网址。但是我没有得到图片网址。

我想从此处获取<div id="gh-banner"> <style> #c4-header-bg-container { background-image: url(//yt3.ggpht.com/5oabquJr1cMEhL0GSyaeim5K78FLxILh4hXJBxIU3NnbpoVLMvquA6l2cbn7cTaFiRNRM2Vy-A=w1060-fcrop64=1,00005a57ffffa5a8-nd-c0xffffffff-rj-k-no); } @media screen and (-webkit-min-device-pixel-ratio: 1.5), screen and (min-resolution: 1.5dppx) { #c4-header-bg-container { background-image: url(//yt3.ggpht.com/5oabquJr1cMEhL0GSyaeim5K78FLxILh4hXJBxIU3NnbpoVLMvquA6l2cbn7cTaFiRNRM2Vy-A=w2120-fcrop64=1,00005a57ffffa5a8-nd-c0xffffffff-rj-k-no); } } #c4-header-bg-container .hd-banner-image { background-image: url(//yt3.ggpht.com/5oabquJr1cMEhL0GSyaeim5K78FLxILh4hXJBxIU3NnbpoVLMvquA6l2cbn7cTaFiRNRM2Vy-A=w2120-fcrop64=1,00005a57ffffa5a8-nd-c0xffffffff-rj-k-no); } </style> </div> 图片网址:

$banner = $html->find('div#gh-banner style',0)->find('#c4-header-bg-container .hd-banner-image')->background-image;

echo $banner;

我正在尝试以下代码:

hd-banner-image

但结果是空的。

如何使用简单的html dom获取{{1}}网址?帮我解决一下。感谢

1 个答案:

答案 0 :(得分:0)

不可能,样式信息在DOM中不可用。它们都只是style标签的内部文本。可以使用正则表达式并允许搜索。

<?php

require getcwd().'/simple_html_dom.php';
$html = '<div id="gh-banner">
    <style>
        #c4-header-bg-container {
            background-image: url(//yt3.ggpht.com/5oabquJr1cMEhL0GSyaeim5K78FLxILh4hXJBxIU3NnbpoVLMvquA6l2cbn7cTaFiRNRM2Vy-A=w1060-fcrop64=1,00005a57ffffa5a8-nd-c0xffffffff-rj-k-no);
        }

        @media screen and (-webkit-min-device-pixel-ratio: 1.5),
        screen and (min-resolution: 1.5dppx) {
            #c4-header-bg-container {
                background-image: url(//yt3.ggpht.com/5oabquJr1cMEhL0GSyaeim5K78FLxILh4hXJBxIU3NnbpoVLMvquA6l2cbn7cTaFiRNRM2Vy-A=w2120-fcrop64=1,00005a57ffffa5a8-nd-c0xffffffff-rj-k-no);
            }
        }

        #c4-header-bg-container .hd-banner-image {
            background-image: url(//yt3.ggpht.com/5oabquJr1cMEhL0GSyaeim5K78FLxILh4hXJBxIU3NnbpoVLMvquA6l2cbn7cTaFiRNRM2Vy-A=w2120-fcrop64=1,00005a57ffffa5a8-nd-c0xffffffff-rj-k-no);
        }
    </style>
</div>';
$html = str_get_html($html);
$style = $html->find('div#gh-banner style',0)->innertext;
$string = preg_match('/hd-banner-image*.*[\s]+background-image:[\s]+url*.*/',$style,$matches);
$substring = substr($matches[0],strpos($matches[0],'(')+1);
$substring = substr($substring,0,strpos($substring,')'));
echo $substring;