首页 > 解决方案 > 从 .txt 文件中拆分条目并使用 php 从 for sitemap.xml 创建一个 foreach 循环

问题描述

我有一个问题,我在 php 中有一个工作的 xml 站点地图生成脚本。条目是通过目录的 foreach 循环生成的。但我需要以这种方式为 .txt 文件执行此操作。拆分 .txt 文件中的条目并为 .txt 文件中的每一行创建一个 for each 循环,以生成 xml 站点地图。

这样看起来我的 .txt 文件:

“价值1”
“价值2”
“价值3”
等。

这是站点地图生成器脚本,我如何以正确的方式拆分 .txt 以使其在每个循环中工作。请需要一些建议或帮助会非常棒。

<?php
            $directory = "pictures/".$_GET['social']."/".$_GET['cat']."/";
            $filecount = 0;
            $files = glob($directory . "*");
            if ($files){
             $filecount = count($files);
            }

//Where to put in .txt file read and split it here?

  header("Content-Type: text/xml");
  function xmlentities($text)
  {
    $search = array('&','<','>','"','\'');
    $replace = array('&amp;','&lt;','&gt;','&quot;','&apos;');
    return str_replace($search,$replace,$text);   
  }
  print chr(60)."?xml version='1.0' encoding='UTF-8'?".chr(62);
  print chr(60)."urlset xmlns='http://www.google.com/schemas/sitemap/0.84' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd'".chr(62);


//here foreach for every line in .txt file?


              foreach (array_slice(glob("pictures/".$_GET['social']."/".$_GET['cat']."/*"), 0, $filecount) as $filename) {
              $data           = getimagesize(str_replace("bilder/thumbs","bilder", $filename));
                    $width          = $data[0];
                    $height         = $data[1];
                    $extension      = image_type_to_extension($data[2]);
                    $imgsize        = filesize(str_replace("bilder/thumbs","bilder", $filename));
                $fileextension = substr($filename, -3);
                $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);

    // create the loc (URL) value based on the foreach loop value, from txt:
    $loc = "https://www.dp-pics.com/".$_GET['social']."/".$_GET['cat']."/".$fileextension."/".lcfirst(basename($withoutExt)).".html";

    print "<url>";
    print "<loc>".xmlentities($loc)."</loc>";
    
    print "</url>";
  }
  print "</urlset>";
?>

标签: phploopsforeachsplittxt

解决方案


推荐阅读