Reputation: 21
I've been trying to figure out how to get the href attribute of a link found on a external webpage.
Here is an example page that I am trying to parse with Xpath:
http://www.shazam.com/track/234782921/lean-on
What I'm trying to get is the following href attribute only of the first element in the list:
<a href="https://www.youtube.com/watch?v=YqeW9_5kURI" class="vd-box vd-play"><span></span></a>
FROM
<div id="trackVideos" class="panel__body">
<ul class="vd-list">
<li class="vd-elm" data-beacon="{"type": "videoclick"}">
<div class="vd-box" style="background-image: url(https://i.ytimg.com/vi/YqeW9_5kURI/hqdefault.jpg);filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=https://i.ytimg.com/vi/YqeW9_5kURI/hqdefault.jpg,sizingMethod=scale);"></div>
<a href="https://www.youtube.com/watch?v=YqeW9_5kURI" class="vd-box vd-play"><span></span></a>
<div class="vd-data">
<p class="vd-title">Major Lazer & DJ Snake - Lean On (feat. MØ) (Official Music Video)</p>
<p class="vd-details">484,920,908 <span>views</span>
</p>
</div>
</li>
<li>SECOND LI</li>
<li>THIRD</li>
</ul>
</div>
This is what I tried:
foreach ($xpath->query("//ul[@class='vd-list']/li[1]/a/@href") as $attr) {
$link = $attr->value;
echo $link;
}
Upvotes: 2
Views: 478
Reputation: 350
I don't know, if the answer is correct I'm giving you, but i think with setting the variable $link
in the foreach, you set it all the time, and nothing will appear...
However, this code should work:
<?php
$a = '<div id="trackVideos" class="panel__body">
<ul class="vd-list">
<li class="vd-elm" data-beacon="{"type": "videoclick"}">
<div class="vd-box" style="background-image: url(https://i.ytimg.com/vi/YqeW9_5kURI/hqdefault.jpg);filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=https://i.ytimg.com/vi/YqeW9_5kURI/hqdefault.jpg,sizingMethod=scale);"></div>
<a href="https://www.youtube.com/watch?v=YqeW9_5kURI" class="vd-box vd-play"><span></span></a>
<div class="vd-data">
<p class="vd-title">Major Lazer & DJ Snake - Lean On (feat. MØ) (Official Music Video)</p>
<p class="vd-details">484,920,908 <span>views</span>
</p>
</div>
</li>
<li>SECOND LI</li>
<li>THIRD</li>
</ul>
</div>';
$xpath = simplexml_load_string($a);
foreach ($xpath->xpath("//ul[@class='vd-list']/li[1]/a/@href") as $attr) {
echo $attr;
}
?>
Upvotes: 1