how to put array data into text file using php - 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
}

Related

Convert JSON array to CSV using PHP

i need to have the csv have the format of the first picture but im currently getting the second picture as a final result, how can i set it properly so MailChimp can read the csv properly
$jsonDecoded = json_decode(file_get_contents('emails.json', true), true);
$list = array(
array('Email Address', 'First Name')
);
$timestamp = time();
foreach($jsonDecoded as $entry)
{
$new = array($entry['email'], $entry['name']);
$list[$timestamp] = $new;
}
//if old file exist delete
$fp = fopen('emails.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Desired Output
Current Output with the above code
The main Issue I can see is you are overwriting the same field in the array, because you are using the same key in the loop
//$timestamp = time(); - only set once, won't change
foreach($jsonDecoded as $entry)
{
// this will update, but won't produce a different key for each iteration,
// because the loop might be faster than the smallest precision
// that the time() function can produce
$timestamp = time();
$new = array($entry['email'], $entry['name']);
$list[$timestamp] = $new;
}
I don't see a use for the timestamp itself, so I suggest just use array_push() or the shorthand shown below
foreach($jsonDecoded as $entry)
{
$new = array($entry['email'], $entry['name']);
$list[] = $new; // this just adds the element to the end of the array
}

How to convert JSON data to CSV format on the fly with out using csv file

I am using PHP and converting the JSON data into the CSV format and later on read the same CSV file for further processing.
Below is my code that converts the JSON data in to the CSV format.
function LoadDataFromFile($file)
{
$json = file_get_contents($file);
$array = json_decode($json, true);
$f = fopen('out.csv', 'w');
$firstLineKeys = false;
$keys = array();
//first collect keys
foreach($array as $line){
foreach($line as $key => $value){
if(!in_array($key, $keys))
$keys[] = $key;
}
}
$keyString = implode(",", $keys);
fwrite($f, "$keyString\n");
foreach ($array as $line)
{
$outputArray = array();
foreach($keys as $key){
if(array_key_exists($key, $line)){
$outputArray[] = str_replace(',', '', $line[$key]);;
} else {
$outputArray[] = "";
}
}
$outputString = implode(",", $outputArray);
fwrite($f, "$outputString\n");
}
fclose($f);
}
As we can see that, i am writing data into the "out.csv" file, and later on i am reading same CSV file and assign the value/ full contents of the same file line by line to $array variable, as shown below.
$array = explode("\n", file_get_contents('out.csv'));
Now, I want to directly assign the value of csv contents into the $array variable with out using the intermediate "out.csv" file.
Wondering what data structure should i use while converting JSON data to CSV format, and possible code changes required for "LoadDataFromFile" method?
If you can already convert the json into csv, then just append the output strings together assigned to a string variable instead of writing it to a file. Or am I misunderstanding what you want?
Instead of:
fwrite($f, "$outputString\n");
you can put:
$csv .= $outputString;
And finish it with:
$array = explode("\n", $csv);

PHP check for a duplicate files in a DIR and write them in a txt

I need to find a duplicate files and write them in a txt file. I almost got it but I can't resolve 4 things.
Every new value must be written in a new line.
An array must be [fileName]=>"fileHash" (Watch p.3)
Write in a txt fileName (a key), not a fileHash.
Why is the first 2 values of $files are . and .. ? They are equal to an empty string.
//get a files array
$files = scandir(__DIR__);
//key=value
$result = array_combine($files, $files);
//get an array of filee hashes
$hashArr = [];
foreach ($result as $file) {
$file = md5_file($file);
array_push($hashArr, $file);
}
//search for duplicates
$arr_unique = array_unique($hashArr);
$arr_duplicates = array_diff_assoc($hashArr, $arr_unique);
//write duplicates in a file
$result = "values.txt";
file_put_contents($result,$arr_duplicates);
In "values.txt" I have
a9f238ec88777a129c1b6ad4ceeef77c57c90c48a63620442e5bddb2764585cb
I tried to make something like this
$fp = fopen('values.txt', 'a+');
fwrite($fp, $arr_duplicates."\r\n");
fclose($fp);
//or
file_put_contents($result,$arr_duplicates . "\r");
but it writes "Array" in my TXT instead of values.
Any help will be appreciated.
//get a files array
$files = scandir(__DIR__);
//key=value no need
// $result = array_combine($files, $files);
unset($files[array_search('.',$files)],$files[array_search('..',$files)]);
//get an array of filee hashes
$hashArr = [];
foreach ($files as $file) {
$fileHash = md5_file($file);
$hashArr[$file] = $fileHash;
// array_push($hashArr, $file);
}
//search for duplicates
$arr_unique = array_unique($hashArr);
$arr_duplicates = array_diff_assoc($hashArr, $arr_unique);
//write duplicates in a file
$fp = fopen('values.txt', 'a+');
foreach($arr_duplicates as $fileName=>$fileHash) {
fwrite($fp, $fileName."\r\n");
}
fclose($fp);
#Jasbeer Rawal
$fileHash = md5_file($file); // is not working for me.
$fileHash = md5_file($dir.$file); //works.
and
$hashArr = array(); // for php < 5.4 $hashArr = [];

PHP renaming string if string already exists

I am storing some data in an array and I want to add the key to it if the title already exists in the array. But for some reason it's not adding the key to the title.
Here's my loop:
$data = [];
foreach ($urls as $key => $url) {
$local = [];
$html = file_get_contents($url);
$crawler = new Crawler($html);
$headers = $crawler->filter('h1.title');
$title = $headers->text();
$lowertitle = strtolower($title);
if (in_array($lowertitle, $local)) {
$lowertitle = $lowertitle.$key;
}
$local = [
'title' => $lowertitle,
];
$data[] = $local;
}
echo "<pre>";
var_dump($data);
echo "</pre>";
You will not find anything here:
foreach ($urls as $key => $url) {
$local = [];
// $local does not change here...
// So here $local is an empty array
if (in_array($lowertitle, $local)) {
$lowertitle = $lowertitle.$key;
}
...
If you want to check if the title already exists in the $data array, you have a few options:
You loop over the whole array or use an array filter function to see if the title exists in $data;
You use the lowercase title as the key for your $data array. That way you can easily check for duplicate values.
I would use the second option or something similar to it.
A simple example:
if (array_key_exists($lowertitle, $data)) {
$lowertitle = $lowertitle.$key;
}
...
$data[$lowertitle] = $local;

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.

Categories