Theon
Theon

Reputation: 1

How to extract a link between paragraph tags

I'm trying to fetch a link which is in between p tags, But my result is "/playlist" and i need the link like "song/54826/father-friend". Been on this for hours now. Help me out please

<div class="track__body">
        <p class="track__track">
            <a href="song/54826/father-friend" class="track__title" id="zwartelijst_song" data-track="">Father &amp; Friend</a>
            <span class="track__artist" data-artist="" id="zwartelijst_artist">Alain Clark</span>
        </p>
        <a href="/playlist" class="track__playlist">
         
        </a>
include('simple_html_dom.php');
$url="some url";
$html = file_get_contents($url);
$links = [];
$document = new DOMDocument;
$document ->loadHTML($html);
$xPath = new DOMXPath($document );
$anchorTags = $xPath->evaluate("//div[@class=\"track__body\"]//a/@href");
foreach ($anchorTags  as $anchorTag) {
    $links[] = $anchorTag->nodeValue;
}
echo $links[1]; 

Upvotes: 0

Views: 45

Answers (1)

user3783243
user3783243

Reputation: 5224

You need to modify your xpath so it scopes to the right element.

$document = new DOMDocument;
$document ->loadHTML('<div class="track__body">
        <p class="track__track">
            <a href="song/54826/father-friend" class="track__title" id="zwartelijst_song" data-track="">Father &amp; Friend</a>
            <span class="track__artist" data-artist="" id="zwartelijst_artist">Alain Clark</span>
        </p>
        <a href="/playlist" class="track__playlist">
        </a>');
$xPath = new DOMXPath($document );
$anchorTags = $xPath->evaluate("//div[@class=\"track__body\"]/p[@class=\"track__track\"]/a/@href");
foreach ($anchorTags  as $anchorTag) {
    echo $anchorTag->nodeValue;
}

https://3v4l.org/YY0dD

Upvotes: 2

Related Questions