Php 在没有元标记描述的站点中提取描述?

Php 在没有元标记描述的站点中提取描述?,php,extract,meta-tags,Php,Extract,Meta Tags,我需要一个php函数来提取一个没有元标记描述的站点url的描述 我已尝试此功能,但不起作用: $content = file_get_contents($url); function getExcerpt($content) { $text = html_entity_decode($content); $excerpt = array(); //match all tags preg_match_all("|<[^>]+>(.*)]+>|", $tex

我需要一个php函数来提取一个没有元标记描述的站点url的描述

我已尝试此功能,但不起作用:

$content = file_get_contents($url);

function getExcerpt($content) {
  $text = html_entity_decode($content);
  $excerpt = array();
  //match all tags
  preg_match_all("|<[^>]+>(.*)]+>|", $text, $p, PREG_PATTERN_ORDER);
  for ($x = 0; $x < sizeof($p[0]); $x++) {
    if (preg_match('< p >i', $p[0][$x])) {
      $strip = strip_tags($p[0][$x]);
      if (preg_match("/\./", $strip))
        $excerpt[] = $strip;
    }
    if (isset($excerpt[0])){
      preg_match("/([^.]+.)/", $strip,$matches);
      return $matches[1];
    }
  }
  return false;
}

$excerpt = getExcerpt($content);
$content=file\u get\u contents($url);
函数getextract($content){
$text=html\u实体\u解码($content);
$EXECRPT=array();
//匹配所有标签
preg_match_all(“|]+>(.*]+>”,$text,$p,preg_模式_顺序);
对于($x=0;$x
您应该首先检查是否有可用的元描述,如果是,则显示该元描述,否则搜索
标记并将该数据显示为描述(您可能希望限制段落长度,例如,如果长度小于30,则搜索下一段)。如果没有
标签,只需将标题显示为描述(这就是facebook和Digg的工作原理)

几乎总是一个坏主意。谢天谢地,PHP有一些库可以为您完成这项工作。下面的代码使用DOMDocument提取元描述,如果元描述不存在,则提取页面中的前1000个字符

<?php
function getExcerpt($html) {

    $dom = new DOMDocument();

    // Parse the inputted HTML into a DOM
    $dom->loadHTML($html);

    $metaTags = $dom->getElementsByTagName('meta');

    // Check for a meta description and return it if it exists
    foreach ($metaTags as $metaTag) {
        if ($metaTag->getAttribute('name') === "description") {
            return $metaTag->getAttribute('content');
        }
    }

    // No meta description, extract an excerpt from the body
    // Get the body node
    $body = $dom->getElementsByTagName('body');
    $body = $body->item(0);

    // extract the contents
    $bodyText = $body->textContent;

    // collapse any line breaks
    $bodyText = preg_replace('/\s*\n\s*/', "\n", $bodyText);
    // collapse any more leftover spaces or tabs to single spaces
    $bodyText = preg_replace('/[    ]+/', ' ', $bodyText);

    // return the first 1000 chars
    return trim(substr($bodyText, 0, 1000));

}

$html = file_get_contents('test.html');

echo nl2br(getExcerpt($html));

你到底想做什么?“提取描述”是什么意思?@Pekka我猜他是想从没有元描述的页面中提取相关的文本片段。如果站点没有元标记描述,我想提取一些文本来描述它定义“不起作用”。如果代码“不起作用”,那么它就被破坏了,不代表您正在尝试做什么,因此我们无法通过阅读它来收集您正在尝试做什么。不要工作,因为我没有得到任何消息