繁体   English   中英

尝试使用preg_match_all对我的服务器php文档使用php动态创建菜单

[英]Trying to create a menu dynamically with php using preg_match_all to my server php documents

该项目包含一个横向菜单,其中包含我的所有博客条目。 从理论上讲,菜单的工作方式如下:我使用php获得了每个博客文档的<h1>标题及其对应的href


因此,每次我添加一个新博客条目时,它将自动出现在菜单中,我使用fopenfread进行了此操作,并将我博客的每个php文档的内容保存在一个名为$ leer的变量中。


然后,我使用Preg_match_all搜索每个博客条目的标题并将其显示在菜单上。 这样,我就可以制作菜单而不必手动添加链接,也可以使用scandir获取url。


问题是,在数组中使用preg_match_all时,给了我许多错误的结果,四次获得相同的<h1>标题而没有解释。 这是代码:

$escanear = scandir ("/home/sites/thetoptenweb.com/public_html/post");
$tamanoArray = count($escanear);

因此,首先,如您所见,我正在使用scandir并进行计数以获得页数。

for($i=2;$i<=$tamanoArray-3;$i++){
    $abrirFichero = fopen($escanear[$i],"r");
    $leer=fread($abrirFichero, filesize($escanear[$i]));        
    fclose($abrirFichero);
}

然后,我使用for循环fread读取我的所有文档。 循环的目的是仅“扫描”第二个和最后一个3之间的选定文件,因为这些是我的博客条目。

preg_match_all('%<h1>(.*)</h1>%', $leer, $arrayMaches);

所以,用preg_match_all功能让我的文档的标题在多维阵列, 该阵列是给我我想的问题,因为我tryed读取与每个结果foreach循环,但也有一些空白的结果和我don'不知道为什么会这样。

foreach ($arrayMaches as $result) {
    foreach ($result as $key) {
    }
}

$cortado=preg_split('%</?h1>%', $key);

echo "<a href=".'"'.$escanear[$i].'"'."><li>".$cortado[0]."</li></a><hr>";

最终,我使用了foreach循环来访问preg_match_all 的多维数组 然后,我preg_split了结果以获取没有html标记的文本,然后,用echo显示结果。

希望有人帮助我识别问题,并在可能的情况下,对preg_match_all数组进行解释,因为我不知道它是如何创建的。 建议被接受。 如果您知道执行此操作的更好方法,我将很高兴阅读它。 这是完整的代码:

<?php
    $escanear = scandir ("/home/sites/thetoptenweb.com/public_html/post");
    $tamanoArray = count($escanear);
    for($i=2;$i<=$tamanoArray-3;$i++){
        $abrirFichero = fopen($escanear[$i],"r");
        $leer=fread($abrirFichero, filesize($escanear[$i]));
        fclose($abrirFichero);
        preg_match_all('%<h1>(.*)</h1>%', $leer, $arrayMaches);
        foreach ($arrayMaches as $result) {
            foreach ($result as $key) {
            }
        }
        $cortado=preg_split('%</?h1>%', $key);
        echo "<a href=".'"'.$escanear[$i].'"'."><li>".$cortado[0]."</li></a><hr>";                  
    }                               
?> 

谢谢。

只需使用DOM ...,您就可以省去一些麻烦。

$menuData = array();
$iter = new DirectoryIterator('/home/sites/thetoptenweb.com/public_html/post');

foreach ($iter as $file) {
   if ($file->isFile()) {
       $filename = $file->getFilename();
       $path = $file->getPathname();
       $dom = new DOMDocument();
       $dom->loadHtmlFile($path);

       $titleNode = $dom->getElementsByTagname('h1')->item(0);
       if ($titleNode) {
          $title = $titleNode->nodeValue;
          $menuData[$filename] = $title;
       }
   }
}

现在,您已经拥有$menuData所有内容,您可以遍历它并输出链接,假设文件名是适当的URL。 另外,您可以直接在循环中输出链接,但是将它们分开是比较明智​​的。 创建一个函数以获取所需的数据,然后使用该数据进行输出。

但是,更好的解决方案是选择一个博客平台并使用它,然后花时间编写一个导入程序并调整外观以适合自己。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM