John Davidson

php - get background-image url from xpath

0 comments
Message:


I tried following code and it returns null.


$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->strictErrorChecking = false;
$doc->recover = true;

ini_set('user_agent', 'My-Application/2.5');
libxml_use_internal_errors(true);
$doc->loadHTMLFile('https://www.revolve.com/elliatt-cassini-dress/dp/ELLI-WD346/?d=Womens&srcType=hp_recs_viewed');
$xpath = new DOMXPath($doc);
$imgs = $xpath->query('//*[@class="zoomWindow "]');
foreach($imgs as $b){
$datae[] = array(
'img' => $xpath->evaluate(
"substring-before(substring-after(./@style, \"background-image: url('\"), \"')\")",
$b
),
);
}


Here's the relevent div element,


<div style="z-index: 999; position: absolute; float: left; height: 536.406px; width: 355.141px; margin-top: 0px; margin-left: 0px; border: 0px solid rgb(136, 136, 136); background-position: -426.067px -499.099px; background-repeat: no-repeat; cursor: crosshair; overflow: hidden; background-image: url("https://is4.revolveassets.com/images/p4/n/z/ELLI-WD346_V1.jpg"); top: 0px; left: 0px; display: none;" class="zoomWindow">&nbsp;</div>


My Answer:
loadHTML($html);_$xpath = new DOMXPath($doc);_$elements = $xpath->query('//div[@class="example"]/style/background-image');foreach ($elements as $element) { $url = $element->getAttribute('url'); echo $url;}This code is incorrect because the XPath query is looking for a `style` element with a `background-image` attribute, which is not valid. Instead, you should be looking for a `div` element with a `background-image` style attribute. Here is the corrected code:$doc = new DOMDocument;_$doc->loadHTML($html);_$xpath = new DOMXPath($doc);_$elements = $xpath->query('//div[@class="example"]/@style[contains(.,"background-image")]');foreach ($elements as $element) { $style = $element->nodeValue; preg_match('/url\((.*?)\)/', $style, $matches); $url = $matches[1]; echo $url;}This code will correctly extract the background-image URL from a `div` element with a `background-image` style attribute.

Rate this post

3 of 5 based on 9416 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us