如何使用PHP从HTML文件中获取元数据


How do I grab meta data from an HTML file using PHP?

我正在尝试在我的网站上创建一个功能,用户可以上传链接,比如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数据库中,我的代码就会中断。你知道我做错了什么吗?提前感谢您的帮助!

它实际上非常简单。

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

大多数人会告诉你使用DomDocument来解析html。尽管我在大多数情况下都同意,但有时使用regex更容易。因此,既然您在问题中使用的是regex,这里有一个regex解决方案。

$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];

这是未经测试的,但在你的情况下应该很好。