希望我对另一个关于同一个旧主题的问题不打扰你。似乎无法弄明白。
只想提前感谢!
我整天都在阅读问题,试图找出如何获取外部网页上找到的链接的href属性。
以下是我尝试使用Xpath解析的示例页面:
http://www.shazam.com/track/234782921/lean-on
我想要得到的只是列表中第一个元素的以下href属性:
<a href="https://www.youtube.com/watch?v=YqeW9_5kURI" class="vd-box vd-play"><span></span></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>
这就是我的尝试:
foreach ($xpath->query("//ul[@class='vd-list']/li[1]/a/@href") as $attr) {
$link = $attr->value;
echo $link;
}
答案 0 :(得分:1)
我不知道,如果答案是正确的我会给你,但我认为在foreach中设置变量$link
,你会一直设置它,什么都不会出现......
但是,此代码应该有效:
<?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;
}
?>