简体   繁体   中英

PHP DOMXpath not picking anything up

I'm trying to write a script that grabs the URL of the first image from this website: http://www.slothradio.com/covers/?adv=&artist=pantera&album=vulgar+display+of+power

Here's my script:

$content = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($content);
$xpath = new DOMXpath($doc);

$elements = $xpath->query("*/div[@class='album0']/img");
echo '<pre>';print_r($elements);exit;

When I run that, it outputs

DOMNodeList Object
(
)

Even when I change my query to $xpath->query("*/img") , I still get nothing. What am I doing wrong?

What am I doing wrong?

You are using print_r , but DOMNodeList does not offer any output for that function (because it's an internal class). You can start with outputting the number of items for example. In the end you need to iterate over the node list and deal with each node on your own.

printf("Found %d element(s).\n", $elements->length);

$doc->loadHTMLFile($content); takes in FILE PATH not HTML content see documentation

http://php.net/manual/en/domdocument.loadhtmlfile.php

Use

$doc = new DOMDocument();
$doc->loadHTMLFile($url);

To Output Element use

var_dump(iterator_to_array($elements)); 
//Or
print_r(iterator_to_array($elements));

Thanks

:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM