Extract href from the html page using php

综合技术 2017-12-31

I trying to extract the news headlines and the link (href) of each headline using the code bellow, but the link extraction is not working. It's only getting the headline. Please help me find out what's wrong with the code.

Link to page from which I want to get the headline and link from: http://web.tmxmoney.com/news.php?qm_symbol=BCM

loadHTML($data);
$dom->preserveWhiteSpace = true;
$xpath = new DOMXPath($dom);
$rows = $xpath->query('//div');

foreach ($rows as $row) {

    $cols = $row->getElementsByTagName('span');

    $newstitle = $cols->item(0)->nodeValue;

    $link = $cols->item(0)->nodeType === HTML_ELEMENT_NODE ? $cols->item(0)->getElementsByTagName('a')->item(0)->getAttribute('href') : '';

echo $newstitle . '
'; echo $link . '

'; } ?>

Thanks in advance for your help!

Try to do this:

loadHTML($data);
  $xpath = new DOMXPath($dom);
  $hrefs= $xpath->query('/html/body//a');

  for($i = 0; $i length; $i++){
   $href = $hrefs->item($i);
   $url = $href->getAttribute('href');
   $url = filter_var($url, FILTER_SANITIZE_URL);

   if(!filter_var($url, FILTER_VALIDATE_URL) === false){
      echo ''.$url.'
'; } } ?>
Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

PHP loop in a messaging function I have an email function that looks like: function send_email_with_attachment($to, $from, $email_a...
Using a php array in a mysql query I'm querying one database to get product stockcodes related to a news article $result = mysql_q...
Learn to code, get paid anywhere So you’ve decided to learn to code so that you can get properly paid for once. Good for you. ...
PHP 调试日志操作类 logId = microtime(); } } /** * 记录时间,方便调试程序执行逻辑和每一步的执行效率 */ public static function _time($label, $h...
PHP 5.6 vs. PHP 7 Performance Comparison It has been awhile over a year since PHP 7 was released. The advanced version that is meant to ...