Reputation: 1
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 & 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
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 & 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;
}
Upvotes: 2