首页 > 解决方案 > 通过 PHP 脚本从目录中获取所有文件名

问题描述

我在托管在 ftp 服务器上的项目中使用 Angular 2+。在入口处,我想将我的 ftp 服务器上某个目录的所有文件名加载到一个数组中,并将其返回给 Typescript。到目前为止,这是我的代码:

文件夹结构:

-scripts
   - getMasterplan.php
-shared_plaene

TS:

    let http = new XMLHttpRequest()
    http.open('POST', Globals.PATH + '/scripts/getMasterplan.php', true)

    // http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    let resp
    http.onreadystatechange = ()=> {

        if(http.readyState == 4 && http.status == 200)
            resp = http.responseText

        console.log('resp',resp)
    }

    http.send(null)

PHP:

<?php

  session_start();

  $files = array();

  $rootDir = "../shared_plaene";

  $path = $rootDir;
  $files = scandir($path);

  echo $files;

?>

responseundefined或_"Array"

已解决:您无法回显数组

标签: phpdirectoryscandir

解决方案


您需要使用PHP scandir 函数

例子

<?php
$dir = "/images/";

// Sort in ascending order - this is default
$a = scandir($dir);

// Sort in descending order
$b = scandir($dir,1);

print_r($a);
//Array ( [0] => . [1] => ..  [2] => cat.gif  [3] => dog.gif  [4] => horse.gif   [5] => myimages )
echo ($a[4]);
// horse.gif

?>

你不能echo一个Array. 如果您print_r改用它,它将使用上述语法打印它


推荐阅读