无法使用getattribute

时间:2016-05-17 10:53:37

标签: php

我正在尝试使用href回显src和图像getattribute但是href得到正确回显,我无法检索图像src .. .plz指南。下面是我的

html样机

<div id="hot-deals">
  <div class="all-deals">
    <ul>
      <li><a href="http://url1.com">
          <img src="http://imagelink1.com"></a>
      </li>
      <li><a href="http://url2.com">
          <img src="http://imagelink2.com"></a>
      </li>
      <li><a href="http://url3.com">
          <img src="http://imagelink3.com"></a>
      </li>
    </ul>
  </div>
</div>

我的代码

$nodes = $my_xpath->query( '//div[@id="hot-deals"]/div[@class="all-deals"]/ul/li/a' );
foreach( $nodes as $node )
    {    
      $title=$node->getAttribute('href');
      $img=$node->getAttribute('img/src');
      echo $title.",".$img."<br>";  
    }

2 个答案:

答案 0 :(得分:2)

src is not attribute of a tag, so you need one more step to get inner img tag and then take its attribute

foreach( $nodes as $node ) {   
  $title = $node->getAttribute('href');
  $imgTags = $node->getElementsByTagName('img');
  $img = $imgTags->item(0)->getAttribute('src');
  echo $title . "," . $img . "<br>";  
}

答案 1 :(得分:0)

您可以尝试使用此代码。

<?php
$str = '<div id="hot-deals">
  <div class="all-deals">
    <ul>
      <li><a href="http://url1.com">
          <img src="http://imagelink1.com"></a>
      </li>
      <li><a href="http://url2.com">
          <img src="http://imagelink2.com"></a>
      </li>
      <li><a href="http://url3.com">
          <img src="http://imagelink3.com"></a>
      </li>
    </ul>
  </div>
</div>';

$nodes = simplexml_import_dom(DOMDocument::loadHTML($str))->xpath('//div[@id="hot-deals"]/div[@class="all-deals"]/ul/li/a');


foreach( $nodes as $node )
{   
  $title = $node['href'];
  $src = $node->img['src'];
  echo $title ." " . $src . '<br>';  
}