Как анализировать фоновые изображения PHP (простой html dom parser) и другие изображения веб-страницы? - PullRequest
1 голос
/ 10 июля 2010

Как анализировать фон PHP (простой html dom / etc ...) и другие изображения веб-страницы?

случай 1: встроенный css

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

вариант 2: CSS внутри html-страницы

<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);
}

case 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.

Если есть еще случаи, напишите их, пожалуйста, с разрешением.

Спасибо

Ответы [ 2 ]

2 голосов
/ 21 июля 2010

Для дела 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.
1 голос
/ 10 июля 2010

Чтобы извлечь <img> со страницы, вы можете попробовать что-то вроде:

$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 для более подробной информации.

...