Search code examples
phpmicrosoft-graph-api

How to download file using MS Graph PHP SDK V2


In V1 I could do

$this->graph->createRequest('GET', '/drives/' . $driveId . '/items/' . $itemId . '/content')->download($path);

How to do this in V2?

I think this is close but I cannot figure out how to write file in $response.

$tokenRequestContext = new \Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext(
    config('graphapi.azure_tenant_id'),
    config('graphapi.azure_client_id'),
    config('graphapi.azure_client_secret')
);

$graphServiceClient = new \Microsoft\Graph\GraphServiceClient($tokenRequestContext);

$response  = $graphServiceClient->drives()
    ->byDriveId(config('graphapi.attachments_drive_id'))
    ->items()
    ->byDriveItemId(<drive_item_id>)
    ->content()
    ->get();

Edit:

$response returns a promise:

object(Http\Promise\FulfilledPromise)#5993 (1) {
  ["result":"Http\Promise\FulfilledPromise":private]=>
  object(GuzzleHttp\Psr7\Stream)#6066 (7) {
    ["stream":"GuzzleHttp\Psr7\Stream":private]=>
    resource(965) of type (stream)
    ["size":"GuzzleHttp\Psr7\Stream":private]=>
    NULL
    ["seekable":"GuzzleHttp\Psr7\Stream":private]=>
    bool(true)
    ["readable":"GuzzleHttp\Psr7\Stream":private]=>
    bool(true)
    ["writable":"GuzzleHttp\Psr7\Stream":private]=>
    bool(true)
    ["uri":"GuzzleHttp\Psr7\Stream":private]=>
    string(10) "php://temp"
    ["customMetadata":"GuzzleHttp\Psr7\Stream":private]=>
    array(0) {
    }
  }
}

So, I changed code to:

$promise  = $graphServiceClient->drives()
    ->byDriveId(config('graphapi.attachments_drive_id'))
    ->items()
    ->byDriveItemId(<drive_item_id>)
    ->content()
    ->get();

$promise->then(
    function ($response) {
        $fileContent = $response->getBody()->getContents();
        file_put_contents('test.txt', $fileContent);
    },
    function ($exception) {
        echo "Error: " . $exception->getMessage();
    }
);

But I get the error: Error Call to undefined method GuzzleHttp\Psr7\Stream::getBody().


Solution

  • For anyone that comes across this and is trying to use V2 of PHP SDK here is solution.

    $tokenRequestContext = new \Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext(
        config('graphapi.azure_tenant_id'),
        config('graphapi.azure_client_id'),
        config('graphapi.azure_client_secret')
    );
    
    $graphServiceClient = new \Microsoft\Graph\GraphServiceClient($tokenRequestContext);
    
    $stream = $graphServiceClient->drives()
        ->byDriveId(config('graphapi.attachments_drive_id'))
        ->items()
        ->byDriveItemId(<drive_item_id>)
        ->content()
        ->get()
        ->wait();
    
    file_put_contents('/path/file_name.txt', $stream);
    

    New docs are here: https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0

    For drive item download:https://learn.microsoft.com/en-us/graph/api/driveitem-get-content?view=graph-rest-1.0&tabs=php#request