【问题标题】:Extract the data from content of HTML从 HTML 内容中提取数据
【发布时间】:2015-12-17 21:28:23
【问题描述】:

我正在尝试从 HTML 中提取数据。我用 curl 做到了,但我只需要将标题传递给另一个变量:

<meta  property="og:url" content="https://example.com/">

如何提取这个,有没有更好的方法?

【问题讨论】:

    标签: php html curl


    【解决方案1】:

    您应该使用解析器从 HTML 文件/字符串/文档中提取值。这是一个使用 domdocument 的示例。

    $string = '<meta  property="og:url" content="https://example.com/">';
    $doc = new DOMDocument();
    $doc->loadHTML($string);
    $metas = $doc->getElementsByTagName('meta');
    foreach($metas as $meta) {
        if($meta->getAttribute('property') == 'og:url') {
            echo $meta->getAttribute('content');
        }
    }
    

    输出:

    https://example.com/

    【讨论】:

      【解决方案2】:

      如果您从远程位置加载 HTML 而不是本地字符串,您可以使用 DOM 来实现此目的,例如:

      libxml_use_internal_errors(TRUE);
      $dom = new DOMDocument;
      $dom->loadHTMLFile('https://evernote.com');
      libxml_clear_errors();
      $xp = new DOMXpath($dom);
      $nodes = $xp->query('//meta[@property="og:url"]');
      if(!is_null($nodes->item(0)->attributes)) {
          foreach ($nodes->item(0)->attributes as $attr) {
              if($attr->value!="og:url") {
                  print $attr->value; 
              }
          }
      }
      

      这会输出期望值:

      https://evernote.com/
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        • 2021-09-09
        • 2012-09-03
        • 2012-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多