【问题标题】:How do I grab meta data from an HTML file using PHP?如何使用 PHP 从 HTML 文件中获取元数据?
【发布时间】:2012-03-18 05:17:32
【问题描述】:

我正在尝试在我的网站上创建一个功能,用户可以在其中上传链接,例如 Digg。我的代码可以从用户上传到我的网站的 URL 中获取 HTML 源代码,并将其存储在 .txt 文件中。然后我想抓取标签中的内容

<meta name="content" description="GRAB THIS"> 

假设这个标签存在。有时它有效,但有时它不起作用,即使该特定网页的源代码包含与我在代码中指定的完全一样的必要元标记。我注意到如果“GRAB THIS”内容包含 html 实体(& 等),它似乎无法正常工作。如果您对如何使其工作有任何想法,请告诉我。这是我的代码:

$html_data = file_get_contents( $path_to_txt_file_that_contains_html );
preg_match( '#<meta name="description" content="(.+?)">#si', $html_data, $tor;
$tor = str_replace ( '<meta name="description" content="' , "", $tor[0] );
$tor = str_replace ( '">', "", $tor );

有时 $tor 仍然包含

<meta name="description" content="CONTENT"

但没有关闭>,所以一旦我将它放入 mySQl 数据库,我的代码就会中断。关于我做错了什么的任何想法?提前感谢您的帮助!

【问题讨论】:

  • 您在 HTML 上使用正则表达式。

标签: php html preg-match file-get-contents str-replace


【解决方案1】:

其实非常简单。

PHP 提供了自己的内置解决方案:http://php.net/manual/en/function.get-meta-tags.php

【讨论】:

  • 感谢您的提醒。我搜索了大约一个小时,从未见过这个。
  • 是的,np。我想这就是您搜索的内容,因为我马上就找到了。
【解决方案2】:

大多数人会告诉你使用 DomDocument 来解析 html。尽管我在大多数情况下都同意,但有时使用正则表达式更容易。因此,由于您在问题中使用了正则表达式,因此这是一个正则表达式解决方案。

$html_data = file_get_contents( $path_to_txt_file_that_contains_html );
preg_match( '#<meta name="description".*content="([^"]+)">#siU', $html_data, $tor);
$tor = $tor[1];

这未经测试,但在您的情况下应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2010-09-18
    • 2012-02-29
    • 2015-04-02
    • 1970-01-01
    • 2016-07-01
    • 2019-12-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    相关资源
    最近更新 更多