Adding columns in out file using php - php

I have created a file file1.out and I am entering data to it.
$parameters is an array containing the parameters name
foreach($parameters as $name)
{
fwrite(file1.out,$name);
//here I am fetching the value of the parameter $name from database
while($row=mysql_fetch_array($result))
{
//getting some values and writing into the file;
}
}
/* this is giving output as
parameter1
1
parameter2
2
parameter3
3
but I want in this way
parameter1 parameter2 parameter3
1 2 3 */
Which special character needs to be written in the file to get a new column after fetching the data of a particular parameter? Please help.

You go to next line in every loop. So store them into a variable and write them to file after foreach
Use something like this:
<?php
$myfile = fopen("sample.txt", "w");
$names = '';
$values = '';
foreach($parameters as $name) {
//fwrite(file1.out,$name);
$names .= "$name \t";
//here I am fetching the value of the parameter $name from database
while($row=mysql_fetch_array($result)) {
$values .= $row[0] . "\t";
//getting some values and writing into the file;
}
}
//Make sure to remove any \n.
$values= str_replace("\n", '', $values);
$names = str_replace("\n", '', $names );
fwrite($myfile, $names . "\n" . $values);
fclose($myfile);

Use 2 varaibles inside the loop to build your strings and use "\t" between text to tab index them :
$param = ''; $vals = '';
foreach($parameters as $name)
{
$param .= '\t\tparameter1\t\t';
$vals .= '\t\t\t' . $name . '\t\t\t';
......
}
Then write $param and $vals to the file after the for loop. You can use any number of \t until you find the suitable presentation.

Related

Php search same values in different array keys

This it´s my little script, but don´t get right results at the moment :
<?php
// Delimiters betweeb data "*" elements in each data delimiters ","
$data_string="house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
// Explode $data_string for "~" delimiter
$data_exp=explode("*",$data_string);
//
// Loop 1
foreach($data_exp as $data_1)
{
$data_exp_compar=explode(",",$data_1);
// We want see the elements with the same data in common in second position (403,404,etc)
$data_common_1[]=$data_exp_compar[1];
$data_common_2[]=$data_exp_compar[1];
}
$a=array_values(array_intersect_key($data_common_1,$data_common_2));
$b=array_count_values(array_intersect_key($data_common_1,$data_common_2));
foreach($a as $aa=>$values)
{
echo $aa;
print "<br>";
}
?>
The idea in this script. It scans the data inside "$data_string", as you can see, all data delimiters is "*" and inside each data we have elements with "," as delimiter
I want get this output results and in this format :
PRODUCT Id: 403 (2 Actually)
1- house1,403,phone1
2- house3,403,phone3
PRODUCT Id: 404 (1 Actually)
1 - house2,404,phone2
Product Id: 405 (1 Actually)
1 - house4,405,phone4
As you can see the only element for compare it´s in the second position and it´s product´s id
I try many things but i can´t get works, or get finally results as i want show
Thank´s in advanced for all , regards
You can group them first then another foreach loop for printing result
$data_string="house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
$data_exp = explode("*",$data_string);
$group = []; // Initialize group array
foreach($data_exp as $data_1)
{
$data_exp_compar=explode(",",$data_1);
$group[$data_exp_compar[1]][] = $data_exp_compar; // Group by the number key after exploding
}
// Loop to each group, then print desired format
foreach ($group as $key => $value) {
echo 'Product ID: ' . $key . ' (' . count($value) . ' Actually)<br>';
foreach ($value as $k => $v) {
echo ++$k . ' - ' . implode(',', $v) . '<br>';
}
echo '<br>';
}
I would suggest using array_map and array_filter functions. Let me know if you have questions about this.
<?php
// Prepare data and input
$id = 403;
$data = "house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
// Convert string data to array
$data = explode("*", $data);
$data = array_map(function ($row) {
return explode(",", $row);
}, $data);
// Search the array
$response = array_filter($data, function ($row) use ($id) {
return $row[1] == $id;
});
print_r($response);

exporting a mysql query in php version 4 to a csv

Edit on my original post. I found the answer!!!! with help:)
I now have this working by using the below code with thanks for the advice on this in the comments:
<?php
$f = fopen('incident_csv\test.csv', 'w');
$query = "
select column1, column2, column3
from table
where columns = values
";
$var1 = mysql_query($query, $database connection variable);
/* From Monkey Zeus */
$csv_lines = array();
// Loop your records from the DB
while ($row = mysql_fetch_assoc($var1)){
$columns = array();
// Loop each column for the row
foreach($row as $k=>$v){
// Surround column item in double-quotes and escape double-quotes with double-double-quotes
$columns[] = '"'.str_replace('"', '""', $v).'"';
}
// Join on a comma
$csv_lines[] = implode(',', $columns);
}
// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);
/* From Monkey Zeus */
fwrite($f, $csv_file_string);
?>
You can do this:
$csv_lines = array();
// Loop your records from the DB
while ($row = mysql_fetch_assoc($var1)){
$columns = array();
// Loop each column for the row
foreach($row as $k=>$v){
// Surround column item in double-quotes and escape double-quotes with double-double-quotes
$columns[] = '"'.str_replace('"', '""', $v).'"';
}
// Join on a comma
$csv_lines[] = implode(',', $columns);
// Write to the file right away. You are using PHP4 so I imagine system memory is not plentiful
// If you use this then there is no need for the "$csv_lines[] =" from above
// nor the $csv_file_string after the while loop
// fwrite($f, implode(',', $columns)."\n");
}
// fclose($f); // If you choose to write to the file during the while loop then close the file handle when you are finished
// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);
You can simply wite an arrayToCsv function:
function arrayToCsv($array) {
$string = array();
foreach ($array as $field) {
$string[] = implode(';', $field);
}
return implode("\n", $string);
}
$a = array(
array('First Field of First Line', 'Second Field of First Line'),
array('First Field of Second Line', 'Second Field of Second Line')
);
fwrite($f, arrayToCsv($a));
But, remember to have your $f setted from $f = fopen('file location', 'w');
Hope I was helpful.

Confusion how to handle array return

function get_galleryxml_row($table_data)
{
$xml_output = array();
if ($table_data)
{
foreach($table_data as $key => $row)
{
$xml_output[] .= $this->exporter->get_property_gallery_data($key['id']);
}
return implode(" ", $xml_output);
}
}
get_property_gallery_data Returns area of images and urls which does contain data and I have checked but some reason i am getting the follow error.
Array to string conversion and it states this line as the error
$xml_output[] .= $this->exporter->get_property_gallery_data($key['id']);
No need of . -
$xml_output[] = $this->exporter->get_property_gallery_data($row['id']); // It should be only $key or $row['id']
It will store the value with new index. . is used to concatenate strings.
Try this...
$xml_output[] .= $this->exporter->get_property_gallery_data($key['id']);
to
$xml_output[] = $this->exporter->get_property_gallery_data($row['id']);

find and replace a specific string of a a particular line in txt file with php

I want to know that how can I replace a specific word/string of a particular line into a text file with php.
Contents of text file is as below:
1|1|1
nikki|nikki#yahoo.com|nikki
nikki|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|nikki
DETAILS OF FIELDS:
COLUMN:0 = $name,
COLUMN:1 = $email,
COLUMN:2 = $nickname,
DETAILS OF REPLACEMENT:
COLUMN:0 = $newName,
COLUMN:1 = $newEmail,
COLUMN:2 = $newnickName,
From the above content you can guess that the find/search is based on the column:1. Ans if match found, than replace the column:0 OR column:2 [based on the choice].
I tried [for finding the column:1]:
$fileData = file("file.txt");
foreach($fileData as $Key => $Val) {
$Data[$Key] = explode("|", $Val);
if ( trim($Data[$Key][1]) == $email ){
unset($fileData[$Key]);
//REPLACE TAKE PLACE HERE
break;
}
}
[for replace]:
/* REPLACE NAME */
$file = "file.txt";
$oname = "|$name|";$nname = "|$newName|";
file_put_contents($file, str_replace($oname, $nname, file_get_contents($file)));
/* REPLACE NICKNAME */
$file = "file.txt";
$onickname = "|$nickname|";$nnickname = "|$newnickname|";
file_put_contents($file, str_replace($onickname, $nnickname, file_get_contents($file)));
But it was replacing all the matching "$name".
I also tried in the following way:
$fileData[$Key] = str_replace($name, $newName, $fileData[$Key]);
file_put_contents($file,$fileData);
/* $name & $newName -:> $nickname & $newnickname
But it doesn't works.
If i want to replace column:0 ["nikki"] of "nikki#gmail.com" with "nikkigmail", then the data should be:
1|1|1
nikki|nikki#yahoo.com|nikki
nikkigmail|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|nikki
And, if want to replace column:2 ["nikki"] of "nikki#hotmail.com" with "hotmail", then:
1|1|1
nikki|nikki#yahoo.com|nikki
nikkigmail|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|hotmail
May i get the code to be corrected ?
Here is how I would replace something like this. Instead of worrying about str_replace, why not actually modify the array returned by file?
<?php
$email = "nikki#gmail.com"; // Search email
$data = file("file.txt", FILE_IGNORE_NEW_LINES); // Read in the data
foreach($data as $key => $line) {
$bits = explode("|", $line);
if($bits[1] === $email) {
// Update this in place,
$bits[0] = "nikkigmail";
$data[$key] = implode("|", $bits);
}
}
$write = implode("\n", $data); // the data to write however you please.
Keep in mind this can also be expanded to suit your row/column needs. For example, you could use something like this.
/**
* The reason these are named differently is because they don't always
* search/replace. For example, you can find nikki#gmail.com in one row,
* but just be setting a different column in that row to a value..
*/
$match = array('col' => 1, 'str' => 'nikki#gmail.com'); // Search data at row
$update = array('col' => 0, 'str' => 'nikkigmail'); // Replace data at row
$data = file("file.txt", FILE_IGNORE_NEW_LINES); // Read in the data
foreach($data as $key => $line) {
$bits = explode("|", $line);
if($bits[$match['col']] === $match['str']) {
// Update this in place,
$bits[$update['col']] = $update['str'];
$data[$key] = implode("|", $bits);
}
}
$write = implode("\n", $data); // the data to write however you please.

how to put array data into text file using php

if i use the following code i got data in text file
{"title":"sankas","description":"sakars","code":"sanrs"}
{"title":"test","description":"test","code":"test"}
but my code is working on
{"title":"sankas","description":"sakars","code":"sanrs"}
so i could not add more rows.where i want to change to get correct results.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
use php's file_put_content() more information here http://php.net/manual/en/function.file-put-contents.php
Update :
assuming that the data is correctly being passed. here is what you can do.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
//using the FILE_APPEND flag to append the content.
file_put_contents ($file, $json, FILE_APPEND);
Update 2:
if you want to access the value back from the text file. overlay.txt here is what you can do
$content = file_get_contents($file);
if you want to fetch title, code, and description separately. and if the string is in json then you need to convert it into array first by using.
//this will convert the json data back to array
$data = json_decode($json);
and to access individual value you can do it like this if you have one row
echo $data['title'];
echo $data['code'];
echo $data['description'];
if you have multiple rows then you can use php foreach loop
foreach($data as $key => $value)
{
$key contains the key for example code, title and description
$value contains the value for the correspnding key
}
hope this helps you.
Update 3:
do it like this
$jsonObjects = file_get_contents('./videos/overlay.txt');
$jsonData = json_decode($jsonObjects);
foreach ($jsonData as $key => $value) {
echo $key . $value;
//$key contains the key (code, title, descriotion) and $value contains its corresponding value
}

Categories