【问题标题】:How to get title from html file using directory - php如何使用目录从 html 文件中获取标题 - php
【发布时间】:2013-05-26 21:17:28
【问题描述】:

对 php 相当陌生,所以请多多包涵。我试图弄清楚如何读取目录/文件夹并将文件名/路径和该文件的标题返回到一个 li。

$handle = opendir('.'); 
while (false !== ($file = readdir($handle))){ 
  $extension = strtolower(substr(strrchr($filename, '.'), 1)); 
  if($extension == 'html' || $extension == 'htm' || $extension == 'php'){ 
      echo "<a href='".$filename."'><li class='"iso_block"'><span>"**Title Tag Here**"</span></li></a>";
  } 
}

^来自 miro 的代码(干杯/感谢)

js.Fiddle 视觉链接:http://jsfiddle.net/AagGZ/547/

【问题讨论】:

  • 你试过glob吗?
  • 在 dom 中加载文件并搜索标题标签(慢)或 preg_match("#(.*)#",...) 它。跨度>
  • jsFiddle 用于测试 php ?你想达到什么目的?
  • jsFiddle 只是一个视觉测试平台(让我在没有任何功能的情况下直观地说明我想要什么)。使用 glob 与 dir 有什么好处?
  • 您需要使用DOMDocument 之类的东西并解析HTML,然后只需定位标题标签并获取内容,应该不难。

标签: php function title page-title


【解决方案1】:
$handle = opendir('.');
$dom    = new DOMDocument();

while (false !== ($file = readdir($handle))){ 
    $extension = strtolower(substr(strrchr($file, '.'), 1));
    if ($extension == 'html' || $extension == 'htm' || $extension == 'php') {
        $title = 'Untitled Document';

        if($dom->loadHTMLFile($urlpage)) {
            $list = $dom->getElementsByTagName("title");
            if ($list->length > 0) {
                $title = $list->item(0)->textContent;
            }
        }

        echo "<a href='$filename'><li class='iso_block'><span>$title</span></li></a>";
    } 
}

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 2017-03-06
    • 2020-05-27
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多