Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReadFiles.php example - Recursion not working #346

Open
devrandomzero opened this issue Jul 10, 2024 · 1 comment
Open

ReadFiles.php example - Recursion not working #346

devrandomzero opened this issue Jul 10, 2024 · 1 comment
Labels

Comments

@devrandomzero
Copy link

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
Copy link
Author

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

@vgrem vgrem added the question label Aug 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants