希望我不要再就同一个老问题来烦你了。好像搞不清楚。
只是想提前说声谢谢!
我整天都在看问题,想知道如何获取外部网页上链接的ref属性。
下面是我试图用Xpath解析的一个示例页面:
http://www.shazam.com/track/234782921/lean-on
我想得到的是列表中第一个元素的以下ref属性:

<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="{&quot;type&quot;: &quot;videoclick&quot;}">
      <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 &amp; 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;
}

最佳答案

我不知道,如果我给你的答案是正确的,但我认为在foreach中设置变量$link时,你一直都在设置它,什么都不会出现。。。
但是,此代码应该可以工作:

<?php

$a = '<div id="trackVideos" class="panel__body">
  <ul class="vd-list">
    <li class="vd-elm" data-beacon="{&quot;type&quot;: &quot;videoclick&quot;}">
      <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 &amp; 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;
}

?>

10-04 18:37