I using PHP 5.5.9-1ubuntu4.22. I am having the following csv file that I read in:
Product;Category;Manufacturer;Price;hasWlan
Product 8;Category 1;Manifacturer - 9;3;f
Product 7;Category 8;Manifacturer - 1;5;t
Product 9;Category 8;Manifacturer - 1;10;t
Product 9;Category 2;Manifacturer - 7;7;f
Product 5;Category 9;Manifacturer - 2;7;t
Product 5;Category 3;Manifacturer - 7;10;t
Product 6;Category 10;Manifacturer - 4;1;t
Product 5;Category 7;Manifacturer - 2;1;t
Product 5;Category 1;Manifacturer - 6;6;t
I would like to replace the following template by the csv values:
Template:
@attr(Product) has the @attr(Category) from the @attr(Manufacturer).
Wanted Result:
Product 8 has the Category 1 from the Manufacturer - 9.
Product 7 has the Category 8 from the Manufacturer - 1.
etc.
I tried the following php script:
<?php
class StringTemplate
{
public function process($text, $singleVariable, $data) {
// 1. Replace Variables
$pattern = '@attr(' . $singleVariable . ')';
$text = str_replace($pattern, $data, $text);
// return final result
return $text;
}
}
/*******************/
/***EXAMPLE USAGE***/
/*******************/
// 1. Read in csv
$csvFile = '/home/ubuntu/workspace/src/SampleText.csv';
echo "\n";
$StringTemplate = new StringTemplate();
$template = "@attr(Product) has the @attr(Category) from the @attr(Manufacturer). ";
$row = 0;
$vars = array();
if (($handle = fopen($csvFile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
echo $StringTemplate->process($template, $vars, $data[$c]);
}
if($row == 0) {
$vars = $data;
echo print_r($vars) . "\n";
}
echo "####################### \n";
$row++;
}
fclose($handle);
}
However, I receive the following output currently:
$ php src/testFile.php
@attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). Array
(
[0] => Product
[1] => Category
[2] => Manufacturer
[3] => Price
[4] => hasWlan
)
1
#######################
@attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). @attr(Product) has the @attr(Category) from the @attr(Manufacturer). #######################
...
As you can see the data does not get replaced within my script.
Any suggestions why this is the case?
I appreciate your replies!
$singleVariableis array.