CSV to Structure Field

I’m trying to import a CSV and convert it to a structure field. Here’s what I have to far based off a few things I’ve found:

<?php

return [
	'description' => 'Import from CSV',
	'args' => [],
	'command' => static function ($cli): void {
		$kirby = $cli->kirby();
		$kirby->impersonate('kirby');
		$site = $kirby->site();
		$parent = page('register');
		$csv = csv('import-users.csv', ';');
		$structure = page('register')->content()->subscribers()->toStructure();
		foreach ($csv as $user) {
			$structure->add([
				'email'     	=> $user['Email'],
				'name'      	=> $user['Name'],
				'orderID'       => $user['OrderID'],
				'datesubscribed' => $user['Paid'],
			]);
	   	}
		try {
			$newPage = $parent->update(['subscribers' => $structure]);
			$cli->success('Users successfully imported!');
		} catch(Exception $e) {
			echo $e->getMessage();
		}
	}
];

I get the success message but the structure field doesn’t update. I can dump everything successfully except the structure field, it just doesn’t seem to be adding anything and shows as empty. Any idea where I’m going wrong, or does anyone have a better way to do CSV → Structure Field?

I think you need to yaml encode it…

$newPage = $parent->update(['subscribers' => Yaml::encode($structure)])

And use the feild as yaml rather then toStructure:

$structure = page('register')->content()->subscribers()->yaml();

Might add that when using yaml (which returns an array instead of a structure object), you cannot use $structure->add() (and that method would require a structure item as param, not an array which you pass to it).

So

$structure = page('register')->content()->subscribers()->yaml();

foreach ($csv as $user) {
    $structure[] = [
	'email'     	 => $user['Email'],
	'name'      	 => $user['Name'],
	'orderID'        => $user['OrderID'],
	'datesubscribed' => $user['Paid'],
			];
}
$newPage = $parent->update([
    'subscribers' => Data::encode($structure, 'yaml'),
]);

Out of curiosity what is the difference between Data::encode and Yaml::encode?

Outcome-wise, none. I forgot to add the type above.

The Data class come with different handlers, yaml, php, json etc., Yaml is such a handler.

1 Like