combine many json files into one - php

I am trying to combine all json files into one.However i always receive an empty json file . Here is code ;
function mergejson()
{
$events = array();
// open each jsonfile in this directory
foreach(glob("*.json") as $filename) {
// get the contents of the the current file
$data[] =json_decode($filename, true);
$events= array_merge($events,$data);
}
$file_name ='merge.json';
$events =json_encode($events,true);
file_put_contents($file_name,$events);
}

The function json_decode takes a string as first argument, not a filename!
So you have to load the file content, try using file_get_contents

Related

How to combine all files in a new file

I want to add all my files that are under "$myfiles" variable in one file called "combined.txt"
I did
echo implode($myfile);
But Im not sure how to make them create and go into a file called "combined.txt"
Use a loop to append the contents of each file to combined.txt.
file_put_contents("combined.txt", ""); // Empty the file first
foreach ($myfiles as $file) {
$contents = file_get_contents($file);
file_put_contents("combined.txt", $contents, FILE_APPEND);
}

multiple JSON files that I would like to parse, edit, and merge into one object,

Hi everyone in stackexhange
i needed multiple .json file decode from folder
I have multiple JSON files that I would like to parse, edit, and merge into one object, which will ultimately get re-encoded and output as a single JSON.
Her my code of one .json file decode
<?php
if ( file_exists( BASE . '/contents/cache/recent-file.json' ) ) {
$recent_file = json_decode( file_get_contents( BASE . '/contents/cache/recent-file.json' ), true );
if ( $recent_file ) {
?>
<div class="items-list">
<?php
foreach( array_reverse($recent_file) as $key => $apps ) {
get_template( 'templates/app-item', $apps );
?>
</div>
<?php } } ?>
You need to:
Get the list of all the JSON files
Get the contents of each file
Add the contents of those files to a PHP array
Output as a new JSON object
My method would be:
//Get all the JSON files
$files = glob("/path/to/folder/*.json");
//Create an empty new array
$newDataArray = [];
//Get the contents of each file
foreach($files as $file){
$thisData = file_get_contents($file);
//Decode the json
$thisDataArray = json_decode($thisData);
//Add $thisData to the new array
$newDataArray[] = $thisDataArray;
}
//Encode the array to JSON
$newDataJSON = json_encode($newDataArray);
Now you can do what you wish with the $newDataJSON object, for example save it to a new .json file:
file_put_contents("/path/to/file.json",$newDataJSON);

How to create multiple files with different names and in different folders? php

So, I have a .txt file with paths of my missing files. I want to write a little php script, that will just create those files and leave them blank.
xxx/yyy/xyxy/a/w/r/obvestilo.pdf
xxx/yyy/xyxy/b/print.pdf
xxx/yyy/xyxy/c/speach.doc
This is an example of how I have things in my .txt file of missing files. I would like the script to create me those files and also folders if they don't yet exist, but I have no clue where to begin. I was thinking to transfer that .txt file to an Array and then loop throug all array elements creating them.
Please try this
$fp = fopen('files.txt','r');
while(($buffer = fgets($fp,4096)) !== false) {
$directory = substr($buffer,0,strrpos($buffer,'/') + 1);
mkdir($directory, 0755, true);
touch(trim($buffer));
}
files.txt will have your files in the format you have in your post.
The mkdir($directory, 0755, true); will create the required directory recursively and the touch will create a blank file.
Try something like the following:
$data = explode("\n", file_get_contents('file_list.txt'));
foreach($data as $filename) {
if(!file_exists(trim($filename))) {
file_put_contents(trim($filename), '');
}
}
That will write an empty string to each file in the list that doesn't already exist so you will get empty files. It won't create directories for you though, if you want to do that you'll need to do something a bit more complicated...
I am assuming that the paths in your .txt file are absolute paths. If not than you will have to append some sort of ROOT_DIRECTORY constant in front of the paths.
Generally you would want to put this functionality in a class whose sole responsibility is to create these empty files:
class EmptyFileCreater {
const USE_RECUSRION = true;
const DEFAULT_ACCESS = 0777;
public function create($path) {
$this->ensureDirectoryExists(dirname($path));
$this->createEmptyFile($path);
}
private function ensureDirectoryExists($directory) {
if (!is_dir($directory)) {
mkdir($directory, self::DEFAULT_ACCESS, self::USE_RECUSRION);
}
}
private function createEmptyFile($path) {
touch($path);
}
}
Now you can use this class to generate all the files.
// Retrieve the .txt file as an array of the lines in the file
$paths = file('path/to/missing_file_paths.txt');
$empty_file_creater = new EmptyFileCreater();
foreach ($paths as $path) {
$empty_file_creater->create($path);
}
This will work for you:
<?php
$lines = file('test.txt'); ///path to your file
foreach ($lines as $line_num => $line)
{
$fp = fopen($line,"wb");
fwrite($fp,'');
fclose($fp);
}
?>
You can use this method to create random names of specific lengths.
/*
*
* Get Random number( 5 digit )
* #param int: 5
* #return alphnumeric string: length(5)
*/
public function getRandomNumber($length, $charset = 'abcdefghijkmnopqrpdctvwxyz3456789') {
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count - 1)];
}
return $str;
}

Check if file exists in .tar using PHP

In my program I need to read .png files from a .tar file.
I am using pear Archive_Tar class (http://pear.php.net/package/Archive_Tar/redirected)
Everything is fine if the file im looking for exists, but if it is not in the .tar file then the function timouts after 30 seconds. In the class documentation it states that it should return null if it does not find the file...
$tar = new Archive_Tar('path/to/mytar.tar');
$filePath = 'path/to/my/image/image.png';
$file = $tar->extractInString($filePath); // This works fine if the $filePath is correct
// if the path to the file does not exists
// the script will timeout after 30 seconds
var_dump($file);
return;
Any suggestions on solving this or any other library that I could use to solve my problem?
The listContent method will return an array of all files (and other information about them) present in the specified archive. So if you check if the file you wish to extract is present in that array first, you can avoid the delay that you are experiencing.
The below code isn't optimised - for multiple calls to extract different files for example the $files array should only be populated once - but is a good way forward.
include "Archive/Tar.php";
$tar = new Archive_Tar('mytar.tar');
$filePath = 'path/to/my/image/image.png';
$contents = $tar->listContent();
$files = array();
foreach ($contents as $entry) {
$files[] = $entry['filename'];
}
$exists = in_array($filePath, $files);
if ($exists) {
$fileContent = $tar->extractInString($filePath);
var_dump($fileContent);
} else {
echo "File $filePath does not exist in archive.\n";
}

Search and replace entire directory file contents

I need to re-write multiple files in a single directory based on the contents of a single CSV file.
For example the CSV file would contain something like this:
define("LANG_BLABLA", "NEW");
In one of the files in the directory it would contain this:
define("LANG_BLABLA", "OLD");
The script will search through the directory and any occurrences where the CSV "LANG_BLABLA" matches the old directory LANG it will update the "OLD" with the "NEW"
My question is how exactly can I list the contents of the files in the directory in 1 array so I can easily search through them and replace where necessary.
Thanks.
Searching through a directory is relatively easy:
<?
clearstatcache();
$folder = "C:/web/website.com/some/folder";
$objects = scandir($folder, SCANDIR_SORT_NONE);
foreach ($objects as $obj) {
if ($obj === '.' || $obj === '..')
continue; // current and parent dirs
$path = "{$folder}/{$obj}";
if (strcasecmp(substr($path, -4), '.php') !== 0)
continue // Not a PHP file
if (is_link($path))
$path = realpath($path);
if ( ! is_file($path))
continue; // Not a file, probably a folder
$data = file_get_contents($path);
if ($data === false)
die('Some error occured...')
// ...
// Do your magic here
// ...
if (file_put_contents($path, $data) === false)
die('Failed to write file...');
}
As for modifying PHP files dynamically, it is probably a sign that you need to put that stuff into a database or in-memory data-store... MySQL, SQLite, MongoDB, memcached, Redis, etc. should do. Which you should use would depend on the nature of your project.
You can parse a CSV file into an array using fgetcsv http://php.net/manual/en/function.fgetcsv.php
First of all I would not recommend this workflow if you working with .php files. Try to centralize your define statements and then change it in a single location.
But here is a solution that should work for you csv files. It's not complete, you have to add some of your desired logic.
/**
* Will return an array with key value coding of your csv
* #param $defineFile Your file which contains multiple definitions e.g. define("LANG_BLABLA", "NEW");\n define("LANG_ROFL", "LOL");
* #return array
*/
public function getKeyValueArray($defineFile)
{
if (!file_exists($defineFile)) {
return array();
} else {
$fp = #fopen($defineFile, 'r');
$values = explode("\n", fread($fp, filesize($defineFile)));
$newValues = array();
foreach ($values as $val) {
preg_match("%.*\"(.*)?\",\s+\"(.*)?\".*%", $val, $matches);
$newValues[$matches[1]] = $matches[2];
}
}
}
/**
* This is s stub! You should implement the rest yourself.
*/
public function updateThings()
{
//Read your definition into an array
$defs=$this->getKeyValueArray("/some/path/to/your/file");
$scanDir="/your/desired/path/with/input/files/";
$otherFiles= scandir($scanDir);
foreach($otherFiles as $file){
if($file!="." && $file!=".."){
//read in the file definition
$oldDefinitionArray=$this->getKeyValueArray($scanDir.$file);
//Now you have your old file in an array e.g. array("LANG_BLABLA" => "OLD")
//and you already have your new file in $defs
//You now loop over both and check for each key in $defs
//if its value equals the value in the $oldDefinitionArray.
//You then update your csv or rewrite or do whatever you like.
}
}
}

Categories