Hello,
I try to scrap a json file and CLI import as pages in Kirby V4.
the import works like a charme but I have a problem to fill a files field with an image.
foreach($news['images'] as $newsImageURL){
// cURL verwenden, um nur die HTTP-Header zu erhalten
$newsImageDownload = curl_init($newsImageURL);
curl_setopt($newsImageDownload, CURLOPT_RETURNTRANSFER, true);
$newsImageData = curl_exec($newsImageDownload);
// Hole den HTTP-Header
curl_close($newsImageDownload);
if ($newsImageData === false) {
$cli->dump('Fehler beim Abrufen des Bildes.');
continue;
}
$tempFile = tempnam(sys_get_temp_dir(), 'img');
file_put_contents($tempFile, $newsImageData);
// MIME-Typ mit finfo_file() ermitteln
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $tempFile);
finfo_close($finfo);
// Extrahiere den MIME-Typ aus den HTTP-Headern
function getExtensionFromMimeType($mimeType) {
$mimeTypes = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/svg+xml' => 'svg',
'image/bmp' => 'bmp',
'image/tiff' => 'tiff',
];
return isset($mimeTypes[$mimeType]) ? $mimeTypes[$mimeType] : 'jpg'; // Standard auf jpg setzen
}
$newsImageFiletype = getExtensionFromMimeType($mimeType);
try{
$imageCreation = File::create([
'source' => $tempFile,
'parent' => $newsEntry,
'filename' => $newsAuthorName.'-'.$news['postedAtISO'].'_'.$n.'.'.$newsImageFiletype
]);
// Überprüfen, ob das Bild erfolgreich erstellt wurde
if (!$imageCreation) {
$cli->dump('Fehler beim Erstellen des Bildes.');
continue;
}
$cli->dump($imageCreation);
$n++;
$newsEntry->update([
'newsarticleheaderimage' => $imageCreation->filename(),
]);
// Temporäre Datei löschen
unlink($tempFile);
} catch (Exception $e) {
$cli->dump('Fehler beim Erstellen der Datei: ' . $e->getMessage());
continue;
}
}
newsarticleheaderimage:
label: Headerimage for the Newsarticle
type: files
multiple: false
layout: cards
query: page.images
I have also tried to use $imageCreation->url()
or [$imageCreation]
. The image is in the created page folder but will not be added to the field in the page txt file.
What did I wrong?
Best