I have been assigned the following PHP task for Uni:
1) Export the Trades/Crafts table to Excel
2) Make three columns in Excel: Trade-ID, Category-ID, Trade-Name and organize it
3) Export the table as a .CSV file (easier for PHP manipulation)
4) Write a PHP script that creates a YAML file from CSV file that corresponds to the structure of AppBundle / Resources / fixtures / prod / trades.ymlHow you do that exactly, is up to you. You are free to use whatever method you prefer, but the YAML file has to have the right structure.
This is the trades.yml file (it was given as an example for us to follow):
-
ref: trade-1
id: 1
name: Plumber
category: $trade-category-1
-
ref: trade-16
id: 16
name: Electronic Engineer
category: $trade-category-2
So as you might have guessed, I have a table with those 3 columns (Trade-ID, Category-ID and Trade-Name). The table contains about 150 rows with the name of many different kind of jobs, the type/branch of the job as category ID, and the ID of the job itself.
I exported that Excel table as a .csv file, as ordered. Now, I think I should use some function like str_getcsv or fgetcsv, which, how I understand it, reads the data in the CSV table and converts it into PHP arrays. After that, I need to convert those arrays into the YAML syntax format, but I read that's not particularly difficult.
Anyways, the number of 'titles/entries' in the YAML structure (ref, id, name, category) does not equal the number of columns in the CSV table (trade name, cat id, trade id), so I don't know how or where I should even start!
Also, for the "ref" part,I guess I would have to make it look like this: trade-<ID of trade> , but how can I do something like "trade-" . $TradeID inside an array? How can declare $TradeID = <ID of the job>? Can I refer to the CSV table's row and column I want, like SELECT in SQL? Or should I maybe use a WHILE loop which fetches all of the table's rows?
I have tried it like this:
<?php
$file = fopen('MyTable.csv', 'r') or die('error');
$line = array();
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
// print_r($line);
foreach ($line as $key => $value) {
# code...
}
}
fclose($file);
But it outputs something like this:
Array ( [0] => 1;1;Bituminiser; ) Array ( [0] => 1;2;Construction Dryer; ) Array ( [0] => 1;3;Concrete Driller and Cutter; ) Array ( [0] => 1;4;Concrete Block and Terrazzo Maker; ) Array ( [0] => 1;5;Well Builder; )
And so on... But I still have the other problem, plus the [0] inside each array.
I really can't figure it out. How can I convert the CSV table into a YAML file with the structure of trades.yml using PHP?