PHP explode with included txt file - php

PHP
When using a txt included file the explode fails. The txt file is just this: a,b,c,d,e
When not an include the string 'explodes' into an array.
$data = include("data.txt");
settype($data,"string");
print "<br><br>type: ".gettype($data)."<br>";
$data = explode(",",$data);
print_r($data);

include() and require() are meant to be used with PHP scripts.
For importing raw data, consider file_get_contents(), which will return a string.

Try
$data = file_get_contents("data.txt");**
print "<br><br>type: ".gettype($data)."<br>";
$data = explode(",",$data);
print_r($data);

Related

I need to include file in array

I tried to include the php file in array like that but it is not working
username.php file is : "mohammed", "ahmed", "hafian", "gimmy", "osama"
and the main file is : $usernames = array(include 'usernames.php');
In usernames.php do:
<?php
return ["mohammed", "ahmed", "hafian", "gimmy", "osama"];
In foo.php do:
$usernames = include 'usernames.php';
RTM: https://www.php.net/manual/en/function.include.php#example-145
You will need to open and read the file, you can't just include and expect it to parse the file and store into your array. Also, can you make usernames.php a text file and not PHP code? You don't want to be parsing PHP code. I think you'll need to approach it like this:
`<?php
$fn = fopen("usernames.txt","r");
while(! feof($fn)) {
$result = fgets($fn);
# parse line and append to array
}
fclose($fn);
?>`

How convert a PHP array of associative array to a CSV string using a third composer vendor lib?

I must convert a php associative array to CSV like:
[
["a"=>1, "b"=>2, "c"=>3],
["a"=>5, "b"=>6, "c"=>6],
["a"=>7, "b"=>8, "c"=>9, "d"=>10]
]
must output a string like
a;b;c;d
1;2;3;
4;5;6;
7;8;9;10
I already implement this logic using only foreach and implodes. However CSV has some features like knowing when scape chars and when to quote cells.
I've been used https://www.papaparse.com/ (javascript) a lot for the front-end side.
Is there a Composer package which can do the job?
PS. I need the CVS as string not to save to a file.
You can use fputcsv to get properly formatted CSV, saving to memory and then save it to a variable:
$fh = fopen('php://memory', 'r+');
foreach($array as $row) {
fputcsv($fh, $row); // add other args as needed
}
$csv = stream_get_contents($fh, -1, 0);
//or
rewind($fh);
$csv = stream_get_contents($fh);
You can also use php://temp which will use memory up to a limit and then write to a temporary file or you can generate your own temporary file with tmpfile.

convert multiple json to php array

I have json file which contains multiple json objects.
Example
{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}
Want to read this file and store into database, but I couldn't convert json to php array which further I can store into database.
I tried json_decode function, but its not working. I search for this but in every link its showing use json_decode. Below is my code
$filename = "folder/filename.json";
$data = file_get_contents($filename);
echo $data;
$tags = json_decode($data, true);
echo"<pre>";print_r($tags);exit;
$data is echoed but not the $tags.
Thanks in advance.
Make array of objects and use it later
$j = array_map('json_decode', file('php://stdin'));
print_r($j);
demo
If it's only four lines you can explode and json_decode each line and add it to an array.
$s = '{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}';
$arr = explode(PHP_EOL, $s);
Foreach($arr as $line){
$json[] = json_decode($line,true);
}
Var_dump($json);
https://3v4l.org/97m0E
Multiple objects in a row should be enclosed in a json array and separated with comma like elements.So you need a [ ] at the start and end of the file.Also you could close the pre tag
Either you should fix the file generating that 'json' or you can use fgets to get one line at a time, and use json decode on every line
As pointed by other, JSON which you shared isn't valid. And, I think, it is stored in your file in same fashion. I would suggest to read this file line by line each line then you can decode.
$handle = fopen("folder/filename.json", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$tags = json_decode($line, true);
echo"<pre>";print_r($tags);exit;
}
fclose($handle);
} else {
// error opening the file.
}
Assuming a file called `filename.json` contains the following lines
{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}
So each one is a separate json entity
$filename = "folder/filename.json";
$lines=file( $filename );
foreach( $lines as $line ){
$obj=json_decode( $line );
$t=$obj->t;
$d=$obj->d;
/* do something with constituent pieces */
echo $d,$t,'<br />';
}
Your JSON is invalid, as it has multiple root elements
Fixing it like the following should work (note the [, ] and commas):
[
{"t":"abc-1","d":"2017-12-29 12:42:53"},
{"t":"abc-2","d":"2017-12-29 12:43:05"},
{"t":"abc-3","d":"2017-12-30 14:42:09"},
{"t":"code-4","d":"2017-12-30 14:42:20"}
]
If you cannot influence how the JSON file is created, you will need to create your own reader, as PHP is not built to support invalid formatting. You could separate the file by new lines and parse each one individually.

How to dump string variables to a text file [duplicate]

This question already has answers here:
How to write into a file in PHP?
(9 answers)
Closed 9 years ago.
I have a series of variables in my PHP script that are defined via POST.
For example:
$From = "";
if( isset($_POST['From']) )
{
$From = $_POST['From'];
}
How can I create a log file (not a database, just basic txt) to capture the POST values? This is part of a conferencing web app, so there is no way to display the content "on screen". I need to dump it to a file on the server.
JSON-encode your array using json_encode() and store it to a file:
$data = json_encode($_POST);
file_put_contents('file.txt', $data);
When you want to retrieve the contents, you can use file_get_contents() or similar and then use json_decode() to decode the JSON-string back into an array / object.
Using JSON makes the interchanging of data easier, and you don't need to parse the text file to retrieve information out of it. Just use json_decode() and be done with it. However, I suggest you use a database instead of a plain text file to store this information, as it gives you more control.
As #Wrikken noted in the comments below, you could use the FILE_APPEND flag - it allows you to append the data to the file instead of overwriting it.
file_put_contents('file.txt', $data, FILE_APPEND);
Try something like this
$post_dump = print_r($_POST, TRUE);
$log = fopen('log.txt', 'a');
fwrite($log, $post_dump);
fclose($log);
Something like this
$arr = array();
foreach($_POST as $key=>$value);
{
$arr[] = $key.'='.$value;
}
file_put_contents('log.txt', implode(',', $arr), FILE_APPEND);
try this...
<?php
$From = "";
if( isset($_POST['From']) ){
$file = fopen("test.txt","w");
fwrite($file,$From);
fclose($file);
}
?>

php file() function creates quotation marks and commas

I'm trying to write some php-code that takes $_GET-data as an input and saves it into a csv-file.
When running the code more than once my csv-file looks like this:
Date,Time,Temperature,"Air Humidity","Soil Humidity",Light,"Wind Direction","Wind Speed",Rain
2013-03-16,16:24:27,12,80,40,82,255,10,0
"2013-03-16,16:24:26,12,80,40,82,255,10,0
","""2013-03-16,16:24:26,12,80,40,82,255,10,0
",""",""""""2013-03-16,16:24:25,12,80,40,82,255,10,0
",""","""""",""""
",""",""""""
","""
"
As you can see, the program adds quotation marks and commas into my data that I don't want. This is apparently done by 'file("weather_data.csv")' but I don't know how to disable or work around this.
This is my code for now:
<?php
// Save received data into variables:
$temperature = $_GET["t"];
$airHumidity = $_GET["ha"];
$soilHumidity = $_GET["hs"];
$light = $_GET["l"];
$windDir = $_GET["wd"];
$windSpeed = $_GET["ws"];
$rain = $_GET["r"];
// Arrays for the column descriptor (first line in the csv-file) and the recent data:
$columnDescriptor = array("Date","Time","Temperature","Air Humidity","Soil Humidity","Light","Wind Direction","Wind Speed","Rain");
$recentData = array(date("Y-m-d"),date("H:i:s"),$temperature,$airHumidity,$soilHumidity,$light,$windDir,$windSpeed,$rain);
$fileContents = file("weather_data.csv");
array_shift($fileContents); // removes first field of $fileContents
$file = fopen("weather_data.csv","w");
fputcsv($file,$columnDescriptor);
fputcsv($file,$recentData);
fputcsv($file,$fileContents);
fclose($file);
?>
$fileContents is read as an array of strings, one entry per line of the CSV file but the actual CSV data is not parsed. The last fputcsv tries to write this data as CSV and escapes it (adding quotes and stuff). You need to add the old file contents ($fileContents) to your file with fwrite instead of fputcsv:
fwrite($file, implode("\n", $fileContents));

Categories