简体   繁体   中英

PHP DOMXPath Query

I am trying to read a href and the img inside that a tag using PHP DOMXPath query.

I am using below to get the "a" tag

$showPage = file_get_contents($url);   
$dom = new DOMDocument();
$dom->validateOnParse = true;
$dom->loadHTML($showPage);  
$dom->preserveWhiteSpace = false;           

$allBollyList = new DOMXPath($dom);
$allBollyTableHTML = $allBollyList->query('//div[contains(@class, "covers")]//a'); 

foreach($allBollyTableHTML as $item) {

    $sourceLink = $item->getAttribute("href");      
} 

However, the "a" in the HTML is as below.

<a href="http://test.com/songs"><img src="http://test.com/test.jpg" alt="Song Name"><div></div></a>

I want to read the "img" tag and read "src" and "alt" inside that "img" tag.

can anyone please help as I am trying to do this in PHP as I am very new?

thanks

Never mind. Finally found the below solution to read "img" tag inside of "a" tag.

    foreach($item->getElementsByTagName('img') as $img){
        echo $img->getAttribute('src') . "\r\n";
    }

So new for loop to read "allBollyTableHTML" will be as below.

foreach($allBollyTableHTML as $item) {

    $sourceLink = $item->getAttribute("href");      

    foreach($item->getElementsByTagName('img') as $img){
        echo $img->getAttribute('src');
    }
} 

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