phpSPO icon indicating copy to clipboard operation
phpSPO copied to clipboard

ReadFiles.php example - Recursion not working

Open devrandomzero opened this issue 1 year ago • 1 comments

Hi, I'm trying to implement the ReadFiles.php example (to retrieve all the files in the document library) but the recursion is not working, only the files in the root folder are retrieved.

Here's the code (near the same as the one in the example, I've omitted just the sensible data):

function forEachFile(Folder $parentFolder, $recursive, callable  $action, $level=0)
{
    $files = $parentFolder->getFiles()->get()->executeQuery();
    /** @var File $file */
    foreach ($files as $file) {
        $action($file, $level);
    }

    if ($recursive) {
        /** @var Folder $folder */
        foreach ($parentFolder->getFolders() as $folder) {
            forEachFile($folder, $recursive, $action, $level++);
        }
    }
}
$ctx = (new ClientContext($siteUrl))->withClientCertificate($tenant, $clientId, $privateKey, $thumbprint);  
$rootFolder = $ctx->getWeb()->getFolderByServerRelativeUrl("Documents");
forEachFile($rootFolder, true, function (File $file, $level) {
     print($level . ":" . $file->getServerRelativeUrl() . "<br>");
 });

These are the screenshots of the document library image image

And this is the output of my php script

0:/sites/docs/Documents/Export1.json
0:/sites/docs/Documents/Document1.docx
0:/sites/docs/Documents/Document2.docx

As you can see it doesn't descend inside the Folder1 & Folder2 folders

Thank you in advance for your help

devrandomzero avatar Jul 10 '24 17:07 devrandomzero

I may have found a solution (just add a single line before the foreach)

if ($recursive) {
      /** @var Folder $folder */
      $folders = $parentFolder->getFolders()->get()->executeQuery();
      foreach ($folders as $folder) {
          forEachFile($folder, $recursive, $action, $level++);
      }
 }

I hope this is the right way

devrandomzero avatar Jul 15 '24 08:07 devrandomzero