PHP Looping CSV to existing Array [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i want to read data from a csv an sort the input to an existing array. Than form the array to a String for, in the next step post it with curl to an existing form. The Problm is i cant get the values from the csv to the string :-( Here's my try:
<?php
$datei = fopen("Testformular.csv", "r");
$data = fgetcsv($datei);
$zeilen = file("Testformular.csv");
$rows= count($zeilen);
$i=1;
while ($i <= $rows){
list($Firma,$Anrede,$Titel,$Vorname,$Nachname,$Strasse,$PLZ,$Telefon,$Fax,$Email,$Nachricht,$CopyFlag) = fgetcsv($fp);
$fields = array(
'tx_btsimplecontact_pi1[name]' => urlencode(""),
'tx_btsimplecontact_pi1[firma]' => urlencode($Firma),
'tx_btsimplecontact_pi1[sex]' => urlencode($Anrede),
'tx_btsimplecontact_pi1[titel]' => urlencode($Titel),
'tx_btsimplecontact_pi1[vorname]' => urlencode($Vorname),
'tx_btsimplecontact_pi1[nachname]' => urlencode($Nachname),
'tx_btsimplecontact_pi1[strasse]' => urlencode($Strasse),
'tx_btsimplecontact_pi1[plz_ort]' => urlencode($PLZ),
'tx_btsimplecontact_pi1[telefon]' => urlencode($Telefon),
'tx_btsimplecontact_pi1[fax]' => urlencode($Fax),
'tx_btsimplecontact_pi1[email]' => urlencode($Email),
'tx_btsimplecontact_pi1[nachricht]' => urlencode($Nachricht),
'tx_btsimplecontact_pi1[copy]' => urlencode($CopyFlag),
'submit' => urlencode("Abschicken")
);
echo "Start at Line:" .$i ."<br/>";
$i++;
foreach($fields as $key=>$value) { $fields_string .= urlencode($key).'='.$value.'&'; }
rtrim($fields_string, '&');
print_r ($string_fields);
echo "Line" .$i ." complete <br/>";
}

Looks to me that you are reading the file into an array three times, once from the existing file pointer using fgetcsv, then you use file() just to count the lines, and then you try to use fgetcsv on a non-existant file pointer.
Here's a quick and dirty edit of your code you can try:
(I'm assuming the CSV-fields are in the order you used in you list()-function.)
<?php
$fp = fopen("Testformular.csv", "r");
$line = 0;
while ( $row = fgetcsv($fp) ) {
// Eliminate the headers
if($line === 0){
$line++;
continue;
}
$output = "";
$output .= 'tx_btsimplecontact_pi1[name]=' . urlencode("");
$output .= '&tx_btsimplecontact_pi1[firma]=' . urlencode($row[0]);
$output .= '&tx_btsimplecontact_pi1[sex]=' . urlencode($row[1]);
$output .= '&tx_btsimplecontact_pi1[titel]=' . urlencode($row[2]);
$output .= '&tx_btsimplecontact_pi1[vorname]=' . urlencode($row[3]);
$output .= '&tx_btsimplecontact_pi1[nachname]=' . urlencode($row[4]);
$output .= '&tx_btsimplecontact_pi1[strasse]=' . urlencode($row[5]);
$output .= '&tx_btsimplecontact_pi1[plz_ort]=' . urlencode($row[6]);
$output .= '&tx_btsimplecontact_pi1[telefon]=' . urlencode($row[7]);
$output .= '&tx_btsimplecontact_pi1[fax]=' . urlencode($row[8]);
$output .= '&tx_btsimplecontact_pi1[email]=' . urlencode($row[9]);
$output .= '&tx_btsimplecontact_pi1[nachricht]=' . urlencode($row[10]);
$output .= '&tx_btsimplecontact_pi1[copy]=' . urlencode($row[11]);
$output .= '&submit=Abschicken';
echo "Line " . $line++ . ": " . $output . PHP_EOL;
}
With this content in the CSV:
Firma,Anrede,Titel,Vorname,Nachname,Strasse,PLZ,Telefon,Fax,Email,Nachricht,Copy‌​Flag
Testfirma1,Herr,Dr.,Vorname1,Name1,Strasse1,11111,12345567,123456,1#keine.de,nac‌​hricht1,1
Gives this result in my terminal:
Line 1: tx_btsimplecontact_pi1[name]=&tx_btsimplecontact_pi1[firma]=Testfirma1&tx_btsimplecontact_pi1[sex]=Herr&tx_btsimplecontact_pi1[titel]=Dr.&tx_btsimplecontact_pi1[vorname]=Vorname1&tx_btsimplecontact_pi1[nachname]=Name1&tx_btsimplecontact_pi1[strasse]=Strasse1&tx_btsimplecontact_pi1[plz_ort]=11111&tx_btsimplecontact_pi1[telefon]=12345567&tx_btsimplecontact_pi1[fax]=123456&tx_btsimplecontact_pi1[email]=1%40keine.de&tx_btsimplecontact_pi1[nachricht]=nac%E2%80%8C%E2%80%8Bhricht1&tx_btsimplecontact_pi1[copy]=1&submit=Abschicken
I put the php in a file (parsefile.php), the CSV in another file (Testformular.csv) and run it in my terminal with php parsefile.php

Related

Input and output format with PHP and SQLSRV

I have a fairly specific scenario that I'm struggling with. The frustration is that it shouldn't even be complicated!
I have a SQL database and I'm connecting to it using PHP + SQLSRV. The database structure is quite straight forward and currently has 2 varchar columns (ColumnA and ColumnB for this example).
My task is to read the data from this table, allow the values to be edited in a form and write back to the database. This part is easy enough and is all working.
The challenge now is that the database values need to be written to my (currently empty) values.php file in the following format.
<?php
$output = array (
"Val1" => 'aaa',
"Val2" => 'bbb',
"Val3" => 'ccc',
);
?>
Ideally, I'd like this to be done at the time of the save to database command which I can do as part of an AJAX success process so that part shouldn't be an issue
I started working on the following process;
<?php
$sql = "SELECT ColumnA, ColumnB FROM Table";
$stmt = sqlsrv_query( $conn2, $sql );
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$test[]= array($row['ColumnA'] ." => '". $row['ColumnB']."',");
$values = implode(PHP_EOL,$test);
}
$content = '<?php
$output = array ("'.$values.'");
?>';
file_put_contents("c:/jjj/values.php", $content);
?>
This gives me a lot of "Array to string conversion" errors and the file gets populated with;
<?php
$output = array ("
Array
Array
);
?>
Where am I going wrong here?
EDIT
After the various comments below, the current code reads as;
<?php
$sql = "SELECT ColumnA, ColumnB FROM Table";
$stmt = sqlsrv_query( $conn2, $sql );
$test = [];
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$test[] = [$row['ColumnA'] => $row['ColumnB']];
}
$content = "<?php" . PHP_EOL;
$content .= "\t" . '$output = [' . PHP_EOL;
foreach($test as $key => $value) {
$content .= "\t\t\"{$key}\" => \"{$value}\"," . PHP_EOL;
}
$content .= "\t];" . PHP_EOL;
$content .= "?>";
file_put_contents("c:/jjj/values.php", $content);
?>
This results in 3 Array to string conversion errors (One for each row) and an output file that looks like this:
<?php
$output = [
"0" => "Array",
"1" => "Array",
"2" => "Array",
];
?>
I still can't find a way to export my DB table to a file in the correct format using PHP.
I think this will come closer to what you want:
To echo tabs as well you could use \t within the double quotes
$content = "<?php" . PHP_EOL;
$content .= "\t" . '$output = [' . PHP_EOL;
foreach($test as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$content .= "\t\t\"{$subkey}\" => \"{$subvalue}\"," . PHP_EOL;
}
}
$content .= "\t];" . PHP_EOL;
$content .= "?>";

Php tags within a variable error

i have been trying to write a php script, i want to add the php code within a variable which requires me to have the php tags within the variable but the following code gives me error because the php tags are getting executed.
here is the code
$current .= " <?php";
$current .= '$CONF = array();';
$current .= '$CONF["host"] = "'.$mysql_host.'";';
$current .= '$CONF["user"] = "'.$mysql_user.'";';
$current .= '$CONF["pass"] = "'.$mysql_pass.'";';
$current .= '$CONF["name"] = "'.$mysql_base.'";';
$current .= "?> ";
file_put_contents("includes/config.php", $current);
Please help me out with this, thanks in advance.
Do not generate PHP code by hand. It is tedious and error-prone. For example, if $mysq_pass contains quotes, the code you put in includes/config.php has syntax errors and doesn't compile.
Use var_export() to produce valid PHP code for a data structure:
$current = "<?php\n" .
'$CONF = '.
// var_export() produces valid code only for the array
var_export(array(
'host' => $mysql_host,
'user' => $mysql_user,
'pass' => $mysql_pass,
'name' => $mysql_base,
), true). // 'true' tells it to return the code, to not echo it
// There is no need to use the PHP closing tag
";\n"
;
file_put_contents("includes/config.php", $current);
See it in action: https://3v4l.org/G5ZoX
You need to provide space in between first two line of code:-
$current .= "<?php";
$current .= ' $CONF = array();';
//-----------^give space here------
You can do in another way
$current .= "<?php ";
//----------------^give space here------
$current .= '$CONF = array();';
For better readability add new-line in each code-line like below:-
$current .= " <?php".PHP_EOL;
$current .= '$CONF = array();'.PHP_EOL;
$current .= '$CONF["host"] = "'.$mysql_host.'";'.PHP_EOL;
$current .= '$CONF["user"] = "'.$mysql_user.'";'.PHP_EOL;
$current .= '$CONF["pass"] = "'.$mysql_pass.'";'.PHP_EOL;
$current .= '$CONF["name"] = "'.$mysql_base.'";'.PHP_EOL;
$current .= "?> ";
file_put_contents("config.php", $current);

PHP: can't decode JSON from string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I wrote this function to build a JSON-style string:
function createJsonFromResponse($response_json)
{
// output json
$output_json = '[';
// number of steps
$num_steps = count($response_json['routes'][0]['legs'][0]['steps']);
//echo $num_steps;
// fill the json
for($i = 0; $i<$num_steps; $i++)
{
// start parenthesis
$output_json .= '{';
// start latitude
$output_json .= '"start_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lat'] . ',';
// start longitude
$output_json .= '"start_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lng'] . ',';
// end latitude
$output_json .= '"end_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lat'] . ',';
// end latitude
$output_json .= '"end_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lng'] . ',';
// step length
$output_json .= '"step_length":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['distance']['value'] . ',';
// html instruction
$output_json .= '"instruction":"' . $response_json['routes'][0]['legs'][0]['steps'][$i]['html_instructions'] . '"';
// closure parenthesis
$output_json .= '}';
// insert comma if required
if($i != $num_steps-1)
$output_json .= ',';
}
$output_json .= ']';
return $output_json;
}
Then, I gave the output string from this function to another one. This second function performs this simple action:
$steps_dec = json_decode($steps_txt,true);
where $steps_txt is the string I produced previously.
Anyway, I testes that the output of json_decode is NULL, while everything work if, in the function producing string, I comment the line adding string field.
It seems to like only numeric field.
can you spot my error?
thanks.
Simplest json in php
$myJson = array('numbers' => array(1, 2, 3));
echo json_encode($myJson);

How to create a SELECT element with an array of options using PHP? [duplicate]

This question already has answers here:
creating variable name by concatenating strings in php
(4 answers)
Closed 8 years ago.
Simple question, with im sure a simple answer, I just cant get it working!!
I have a function which will be passed one of 5 id's (for example "first", "second", ",third", "fourth" and "fifth").
Inside this function I want to refer to an array whose name is the id followed by _array (for example "first_array", "second_array" etc...)
How do I concatenate the id name passed to the function with the string "_array" ? I know how to do this in a string but not when referring to another variable!
To sum up i will have:
$i_d = "first" //passed to my function
$string = "_array"
and I want to link to an array called:
$first_array
EDIT
My code is the following:
$option_timescale = array ( "1"=>"Immediately",
"2"=>"1 Month",
"3"=>"2 Months",
"4"=>"3 Months",
"5"=>"4 Months",
"6"=>"5 Months",
"7"=>"6 Months",
"8"=>"No Timescale"
);
$option_bus_route = array ( "1"=>"1 minute walk",
"2"=>"5 minute walk",
"3"=>"10 minute walk",
"4"=>"No Bus Needed"
);
$option_train_stat = array( "1"=>"5 minute walk",
"2"=>"10 minute walk",
"3"=>"5 minute drive",
"4"=>"10 minute drive",
"5"=>"No Train Needed"
);
function select_box($k,$v){ //$k is the id and $v is the description for the select boxes label
$string = "option_"; //these two lines
$option_array =$string . $k; //are the troublemakers!
$buffer = '<select name="' . $k . '" id="' . $k . '">';
foreach ($option_array as $num=>$desc){
$buffer .= '<option value="' . $num . '">' . $desc . '</option>';
}//end foreach
$buffer .= '</select>';
$buffer .= '<label for="' . $k . '">' . $v . '</label>';
return $buffer;
}//end function
And the code which calls this function is:
function create_table($titles, $id) { //$titles is the relevant array from lists.php, $id is the id of the containing div
$select = array('timescale','bus_route','train_stat'); //'select' id list
$textarea = array('notes'); // 'textarea' id list
$buffer = '<div id="' . $id . '">';
foreach ($titles as $k=>$v) { //$k is the database/id/name $v is the description text
if (in_array($k,$select)){
$buffer .= select_box($k,$v);
}
else if (in_array($k,$textarea)){
$buffer .= text_box($k,$v);
}
else{
$buffer .= check_box($k,$v);
}
}
$buffer .= '</div>';
echo $buffer;
}
Add $ to eval the string.
$i_d = "first";
$string = "_array";
$myvar = $i_d . $string;
$$myvar = array('one','two','three');
print_r( $$myvar);

updating a file in specific part only in php

I need to update a file using php
Sample file:
#Start#
No. of records: 2
Name: My name,
Age: 18,
Date: 2013-07-11||
Name: 2nd name,
Age: 28,
Date: 2013-07-11||
#End#
I need to edit 'No. of records' on each time I add another record on file. And another record needs to be before '#End#'
I'm using
$Handle = fopen($File, 'a');
$data = .......
fwrite($Handle, $Data);
to add records
How can I edit 'No. of records' & add data before '#End#'?
Instead of modifying the file I would parse it, change the data in PHP an rewrite the file after that.
To achieve this, I would firstly create a function that parses the input into php arrays:
function parse($file) {
$records = array();
foreach(file($file) as $line) {
if(preg_match('~^Name: (.*),~', $line, $matches)) {
$record = array('name' => $matches[1]);
}
if(preg_match('~^Age: (.*),~', $line, $matches)) {
$record ['age'] = $matches[1];
}
if(preg_match('~^Date: (.*)\|\|~', $line, $matches)) {
$record ['date'] = $matches[1];
$records [] = $record;
}
}
return $records;
}
Secondly I would create a function that flattens the arrays back into the same file format again:
function flatten($records, $file) {
$str = '#Start#';
$str .= "\n\n";
$str .= 'No. of records: ' . count($records) . "\n\n";
foreach($records as $record) {
$str .= 'Name: ' . $record['name'] . ",\n";
$str .= 'Age: ' . $record['name'] . ",\n";
$str .= 'Date: ' . $record['name'] . "||\n\n";
}
file_put_contents($file, $str . '#End#');
}
Then use it like this:
$records = parse('your.file');
var_dump($records);
$records []= array(
'name' => 'hek2mgl',
'age' => '36',
'date' => '07/11/2013'
);
flatten($records, 'your.file');
In case if file is relatively small (easily fits in memory), you can use file() function. It will return array, which you can iterate, etc.
If the file is larger, you'll need to read it in the loop using fgets(), writing data to the new temporary file and replacing original file with it after you're done

Categories