Dynamically compose the name of function to call on php - php

I have csv like this.
id,startScore,endScore,total
1,12,34,46
2,10,20,30
.
.
Now I have Entity with the same column name.
So,it has the functions like these below.
setStartScore()
setEndScore()
setTotal()
For now my php code is like this below
$lines = explode('\n',$csvFile); // get CSV Content
$header = array_shift($lines); // get header
$headers = explode(",",$header)
foreach($lines as $line){ // each csv line
$table = new Table();
foreach(explodes(',',$line) as $l){
$i = 0;
foreach($headers as $h){
$table->set{$headers[$i]}($l[$i]) //how can I make dynamically make set***() function.
$i++;
}
I guess if I get doctrine setter/getter naming regulation, it works well though....

You can use a constructor to set the data.
Class Table
// ..
public function __construct($id, $startScore, $endScore, $total){
$this->id = $id;
$this->startScore = $startScore;
$this->endScore = $endScore;
$this->total = $total;
}
Then you can create the objects like:
foreach($lines as $line){ // each csv line
$data = explodes(',',$line);
$table = new Table($data[0], $data[1], $data[2], $data[3]);
$em->persist($table);
}
// ..flush

Related

PHP export products from database into csv

I have to export all my products from database into a csv file when executing the following script but i can't manage to put together the function that returns all my products from database into an array or iterator. My php code is put below. What am i doing wrong? Thank you.
<?php
require_once("config/db-connect.php");
function toate_produsele_active() {
$array_produse = mysqli_query($mysqli, "SELECT product_id, product_name, category_url, product_short_desc, product_price, product_photo FROM mb95_products");
while ($row = mysqli_fetch_assoc($array_produse)) {
print_r($row);
}
}
$f = fopen('php://output', 'wb');
if($f) {
foreach(toate_produsele_active() as $produs) {
$coloane = array(
$produs['product_id'],
$produs['product_name'],
$produs['category_url'],
$produs['product_short_desc'],
$produs['product_price'],
implode('[,]', str_replace('[,]', '[%2C]', $produs['product_photo'])),
);
fputcsv($f, $coloane, ';', '"');
}
fclose($f);
}
?>
My final desired result should look something like this:
1;Titlu produs1;categorie;Descriere produs1;RON;60;5;product_photo.jpg
let's say that toate_produsele_active() it's working as expected. I have created three functions, so the code can be reused and i have added the comments in the code:
<?php
// Create the header for the csv file (ID, Titlu, Descriere, Pret)
function getHeader()
{
$csv = '';
$headerData = array();
$header = 'ID, Titlu, Descriere, Pret';
$columns = explode(',', $header);
foreach ($columns as $column) {
$headerData[] = $column;
}
// the titles are separated by the semicolon
$csv .= implode(';', $headerData) . "\n";
return $csv;
}
// add the products data into an array and then fill the csv file
// with rows. Separated by semicolon
function iterateItems($csv)
{
$data = [];
foreach (toate_produsele_active() as $produs) {
$data[] = $produs['product_id'];
$data[] = $produs['product_name'];
$data[] = $produs['category_url'];
$data[] = $produs['product_short_desc'];
$csv .= implode(';', $data) . "\n";
}
return $csv;
}
function exportAll()
{
// name and location of the file
$csvFile = 'products.csv';
// create the header: ID, Titlu, Descriere, Pret
$csvHeader = getHeader();
// add the header and then the product data into the csv file
$csv = iterateItems($csvHeader);
// save he file (location, file)
file_put_contents($csvFile, $csv);
}
// call the function
exportAll();

How to create custom CSV files using PHP?

In the $csv_array_attributes[0] represents every column for my csv file. sku is the product id. In $csv_array_attributes[0] represents all of the product ids for my csv(which is the rows value form column sku). In the query below I extract all of the products ids, attributes names and attributes values. My problem is that I have to compute my $csv array in order to assign for each attribute name(columns) the attribute values. In $final_string somehow I want to memorize all of the attributes values for a products (see the commented part). Thx in advance for the help. Im really stuck with this :(
$csv_array_attributes[0] = "sku%%".$header;
//GETTING ATTRIBUTES VALUES
$i = 1;
foreach($xml->children() as $content){
$id_produs = $content->ProductCode;
$csv_array_attributes[$i] = $id_produs;
$i++;
}
$select = mysql_query("SELECT id_prod.id_produs, GROUP_CONCAT('^^',nume_attr) AS nume_at, GROUP_CONCAT('^^',val_attr) AS val_at FROM attributes
INNER JOIN id_prod
ON id_prod.id_id_produs = attributes.id_produs
GROUP BY id_prod.id_produs");
$i = 0; $id_prod = array();
while ($row = mysql_fetch_array($select)){
$id_produs = $row['id_produs'];
$nume_attr = explode(",^^",substr($row['nume_at'],2));
$val_attr = explode(",^^",substr($row['val_attr'],2));
$id_prod[$id_produs] = $nume_attr;
$i++;
}
// var_dump(count($id_prod));
$nume = explode("%%", $csv_array_attributes[0]);
$csv[0] = $csv_array_attributes[0];
$i = 1;
foreach ($id_prod as $key => $value) {
// comment part
//$final_string = "";
//if (attr_name has attribute_value for product i ){
// $final_string.= attribute_value."%%";
//}else{
// $final_string.= "%%";
//}
//end comment part
$csv[$i] = $csv_array_attributes[$i]."%%".$final_string;
$i++;
}
//var_dump($csv_array_attributes[0])
//CREARE CSV
$file = fopen("attributes.csv","w+");
foreach ($csv as $line){
fputcsv($file,explode('%%',$line),"^","`");
}
To see the current result please click HERE
Actually I only can give you a hint how I would create a array for csv.
// header
$csv[0][0] = "one";
$csv[0][1] = "two";
$csv[0][2] = "three";
$csv[0][3] = "four";
$csv[0][4] = "five";
// body
$csv[1][0] = "some";
$csv[1][1] = "values";
$csv[1][2] = "that";
$csv[1][3] = "could";
$csv[1][4] = "be";
$csv[2][0] = "here";
$csv[2][1] = "in";
$csv[2][2] = "this";
$csv[2][3] = "little";
$csv[2][4] = "array";
This is only a sample to view the array setup.
If you have set up the header, lets say by a for you can fill the 2 demensional array.
If this is set up you can use a foreach to build your CSV
Sample
$seperator = ";";
$ln = "\r\n";
$csv_output = "";
foreach($csv as $c){
foreach($c as $value){
$csv_output .= $value . $seperator;
}
$csv_output . $ln;
}
csv output
one;two;three;four;five;
some;values;that;could;be;
here;in;this;little;array;
a row;with an;;empty;field;
empty fields are no problem since you seperate them all with a ;

How can i print an array passed from a page to FPDF

My fpdf.php file is
<?php
require('fpdf/fpdf.php');
$prod_data = array();
if($_POST['affiliate_pdf']){
$prod_data = unserialize($_POST['affiliate_pdf']);
}
class PDF extends FPDF
{
public $prod_data;
public function createData($input){
$this->prod_data = $input;
}
function Header()
{
// Page header
global $title;
$this->SetFont('Arial','B',15);
$w = $this->GetStringWidth($title)+6;
$this->SetX((210-$w)/2);
$this->SetDrawColor(0,80,180);
$this->SetFillColor(230,230,0);
$this->SetTextColor(220,50,50);
$this->SetLineWidth(1);
$this->Cell($w,9,$title,1,1,'C',true);
$this->Ln(10);
// Save ordinate
$this->y0 = $this->GetY();
}
// Load data
function LoadData($file)
{
// Read file lines
$lines = file($file);
$data = array();
foreach($lines as $line)
$data[] = explode(';',trim($line));
return $data;
}
}
$pdf = new PDF();
// Column headings
$title = 'Title';
$header = array('AFFILIATE CHANNELS', 'TOTAL CHANNEL REVENUE', 'TOTAL SHARE OF REVENUE', 'TOTAL AFFILIATE SHARE OF REVENUE');
// Data loading
$data = $pdf->LoadData('countries.txt');
$pdf->SetFont('Arial','',14);
$pdf->AddPage();
$pdf->Cell(10,10,'Affiliate Name', 0,0,'L');
$pdf->Output();
?>
affiliate_pdf is my array which i am passing to fpdf.php . Here i want to use its values. So, i just want to ask , how can i print this array in $pdf->Cell or can i write it at any other place.
Mainly i just want to print its value on this pdf. It may be in any array format.
You can use print_r(). By defaut, it print array values but you can set a param to return values.
$pdf->Cell(10,10,print_r($your_array, true), 0,0,'L');

Probleam using classes , array , json and php

Hi, this is my first time trying to create some code in PHP and it took me a long time but I'm able to convert data to xml. Now I need create a JSON object and it's not going well. The biggest problem is trying to create a new class in PHP (I don't know if what I did is ok or not) and if this is the correct way to attach a list. I think some of it's good but to me since I only use java and c# it seems a little crazy. I think I'm doing something wrong. The line that's showing me an error is $array['data']->attach( new Cake($name,$ingredients,$prepare,$image)); but i don't know what I'm doing wrong.
I haven't yet written the line that includes and transforms the array into json
Thanks
//opens the file, if it doesn't exist, it creates
$pointer = fopen($file, "w");
// writes into json
$cake_list['data'] = new SplObjectStorage();
for ($i = 0; $i < $row; $i++) {
// Takes the SQL data
$name = mysql_result($sql, $i, "B.nome");
$ingredients = mysql_result($sql, $i, "B.ingredientes");
$prepare = mysql_result($sql, $i, "B.preparo");
$image = mysql_result($sql, $i, "B.imagem");
// assembles the xml tags
// $content = "{";
// $content .= "}";
$array['data']->attach( new Cake($name,$ingredients,$prepare,$image));
// $content .= ",";
// Writes in file
// echo $content;
$content = json_encode($content);
fwrite($pointer, $content);
// echo $content;
} // close FOR
echo cake_list;
// close the file
fclose($pointer);
// message
// echo "The file <b> ".$file."</b> was created successfully !";
// closes IF($row)
class Cake {
var $name;
var $ingredients;
var $prepare;
var $image;
public function __construct($name, $ingredients, $prepare, $image)
{
$this->name = $name;
$this->ingredients = $ingredients;
$this->prepare = $prepare;
$this->image = $image;
}
}
function create_instance($class, $arg1, $arg2, $arg3, $arg4)
{
$reflection_class = new ReflectionClass($class);
return $reflection_class->newInstanceArgs($arg1, $arg2,$arg3, $arg4);
}
The error you are experiencing is because you are doing $array['data'] when you mean $cake_list['data'] so change the error line to:
$cake_list['data']->attach(new Cake($name, $ingredients, $prepare, $image));
Also a simple way to simple way to create a JSON object (or more accurately a string representation of a JSON object) is to do this:
$array = array(
'name' => $name,
'ingredients' => $ingredients,
'prepare' => $prepare,
'image' => $image
);
$json = json_encode($array);
You can also create simple easy to use objects like this:
$myObject = new stdClass(); // stdClass() is generic class in PHP
$myObject->name = $name;
$myObject->ingredients = $ingredients;
$myObject->prepare = $prepare;
$myObject->image = $image;

PHP read in specific csv file column as an array

I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.
I would like to get all the values from the second column only, without the heading.
Any way of doing this?
This is what I have so far:
$file = fopen('data.csv', 'r');
$line = fgetcsv($file);
And this is some sample data from the csv file:
ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00
Any help would be appreciated.
Thanks.
fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:
$data = array();
while($row = fgetcsv($file)) {
$data[] = $row;
}
The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:
$data[] = $row[1];
However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:
$data[$row[0]] = $row[1];
and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.
$csv = array_map("str_getcsv", file("data.csv", "r"));
$header = array_shift($csv);
// Seperate the header from data
$col = array_search("Value", $header);
foreach ($csv as $row) {
$array[] = $row[$col];
}
// Iterate through data set, creating array from Value column
$header = fgetcsv($h);
$rows = array();
while ($row = fgetcsv($h)) {
$rows []= array_combine($header, $row);
}
$fp = fopen($filePath, "r+");
$header = fgetcsv($fp);
while ($members = fgetcsv($fp)) {
$i = 0;
foreach ($members as $mem) {
$membersArray[ $i ][ ] = $mem;
$i++;
}
}
$newArray = array_combine($header, array_map("array_filter",$membersArray));
You can also use this class http://code.google.com/p/php-csv-parser/
<?php
require_once 'File/CSV/DataSource.php';
$csv = new File_CSV_DataSource;
$csv->load('data.csv');
var_export($csv->connect());
?>

Categories