How to get the image file of a ticket article attachment via Zammad API

Found the solution. In short:
I actually need to access the “body” or content of the GuzzleHttp\Psr7\Stream Object that I receive with article method: getAttachmentContent(‘attachment_id’).

In case anyone else has this problem to solve, I’ll post my long version of the solution below using the Zammad API PHP Client. If anyone has a more elegant solution, I’d be interested.

// Get the ticket object.
$ticket = $client->resource( ResourceType::TICKET )->get($ticket_id);

// Get the ticket articles. 
$ticket_articles = $ticket->getTicketArticles();

// Loop $ticket articles to get the article attachments.
foreach($ticket_article_ids as $key => $article_id) {

	// Get an article object.
	$article = $client->resource( ResourceType::TICKET_ARTICLE )->get($article_id);

	// Get the article attachments (array).
	$article_attachments = $article->getValue('attachments');

	// Loop the article attachments.
	foreach($article_attachments as $key => $attachment) {

		// Get the attachment content. 
		// Note: This returns a GuzzleHttp\Psr7\Stream Object
		$attachment_content = $article->getAttachmentContent($attachment['id']);

		// Get the Guzzle object "body" or contents, in my case the image file.
		$guzzle_contents = $attachment_content->getContents();

		// .. process the image file .. i.e. store on server under new name.
		$server_filename = "./files/ticket123-article45-" . $attachment['filename'];
		
		// Response contains the amount of bytes of the file or FALSE.
		$response = file_put_contents($server_filename, $guzzle_contents)
		
		// ... do some more stuff ..
	}
}
2 Likes