【问题标题】:php - get a link's valuephp - 获取链接的值
【发布时间】:2016-01-22 09:26:22
【问题描述】:

我正在使用 php 来获取 html 文件的一部分:

HTML 文件:

<div class="titles">
    <h2><a href="#">First Title</a></h2>
</div>

PHP 文件:

<?php
    include_once('simple_html_dom.php');
    $url = 'http://example.com';
    $html = file_get_html($url);
    $titles = $html->find('.titles');
    $heading = $titles->find('h2')[0];
    $link = $heading->find('a')[0];
    echo $link; 
    //result: <a href="#">First Title</a>
?>

如何分别获取href和'a'标签的值?

因为我想把标题和链接保存到数据库中,

我需要 '#' 和 'First Title' 而不是 'a' 标签。

【问题讨论】:

    标签: php html


    【解决方案1】:

    $link 应该是一个简单的 HTML 元素 object,您可以使用 $link-&gt;href 访问其属性,文本内容为 $link-&gt;plaintext。见http://simplehtmldom.sourceforge.net/manual.htm

    【讨论】:

      【解决方案2】:

      你可以使用 DOMDocument 和 DOMXpath 对象的 (>=php5)

      参考:http://php.net/manual/en/class.domdocument.php

      部分示例代码:

      $html = '<div class="titles">
      <h2><a href="#">First Title</a></h2>
      </div>';
      
      
      $page = new DOMDocument();
      $page->loadHtml($html);
      
      $xpath = new DOMXpath($page);
      $a = $xpath->query("//a");
      
      for ($i=0; $i < $a->length; $i++) {
          $_a = $a->item($i);
      
          echo  $_a->getAttribute("href");
          echo "<br>";
          echo  $_a->textContent;
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-07
        • 1970-01-01
        • 1970-01-01
        • 2013-10-12
        • 2014-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多