Array to string conversion fwrite php - php

Good day!
I am trying to print the array on the text file but whenever I try to run my code, I would always get this error
Notice: Array to string conversion in <path>
It would point to this line of code:
fwrite($listonedupe, $result1.PHP_EOL);
What could be the possible solution for this?
<?php
$getapps = 'B:\z.test\runningapps.txt';
$fordupe = 'B:\z.test\fordupe.txt';
$sendtoserver = 'B:\z.test\sendtoserver.txt';
if ($file1 = fopen($getapps, "r"))
{
$read1 = fread($file1,filesize($getapps));
$line1 = explode("\n", $read1);
$file2 = fopen($fordupe, "r");
$read2 = fread($file2,filesize($fordupe));
$line2 = explode("\n", $read2);
$result1 = array_diff($line1, $line2);
if (count($result1)>0)
{
$forserver = fopen($sendtoserver,"w");
foreach ($result1 as $value1) {
fwrite($forserver, $value1.PHP_EOL);
// for checking server
$s1 = fopen($sendtoserver, "r");
$s2 = fread($s1,filesize($sendtoserver));
$s3 = explode("\n", $s2);
var_dump($s3);
$listonedupe = fopen($fordupe,"a");
fwrite($listonedupe, $result1.PHP_EOL);
}
// for checking dupe
var_dump($line2);
}
else
echo "ok";
}else
die("Unable to open file!");
?>

Replace fwrite($listonedupe, $result1.PHP_EOL); to fwrite($listonedupe, $value1.PHP_EOL);

Related

How can I open a file with a variable (array) name on php?

I tried write a php script for taking 1 main file from server and read this file, explode it(with ":" character) and keep it a array then I write this variables in array to a txt file each new line. Then I can read this file line by line but I can't open any file with fopen($variable, 'r');. My variable is; $variable = $array[1]."txt";.
My codes;
<?php
$file = file("toplist.txt");
$countLine = count($file);
$userMain = array();
$userMain[0] = "Top List";
$userNames = array();
$userNames[0] = "SampleName";
for ($i=1;$i<$countLine;$i++){
$user = explode (":",$file[$i],-1);
$userMain[$i] = $user[0];
echo $userMain[$i]."<br>"; //Test echo
}
$totalLn = count($userMain);
echo $totalLn; //Echo total line.
$myFile = $userMain[1].".txt";
$fileAA = fopen($myFile,'r');
while($line = fgets($fileAA))
$data[] = $line;
fclose($fileAA);
for ($counter = 0; $counter <= 5 ; $counter++ )
{
echo "<i>".$data[$counter]."</i><br />";
}
?>
My toplist.txt file;
toplist:
54df3a11-3ea0-37c4-8ec4-0fdd45f2e069: 211
and I have a file with a 54df3a11-3ea0-37c4-8ec4-0fdd45f2e069.txt named.
And 54df3a11-3ea0-37c4-8ec4-0fdd45f2e069.txt file contents;
name : SampleName123
destination : SampleDestination
SampleContent : SampleContent
I need the name line and just SampleName123.
$contents = file_get_contents($array[1]."txt");
$rows = explode("\n",$contents);
$user = [];
foreach($rows as $row){
$parts = explode(" : ",$row);
$user[$parts[0]] = $parts[1];
}
After this parsing you can access user as an array.
$user['name']
And you can do the listing as well:
$file = file($user['name'].".txt"); //Reads entire file into an array
foreach($file as $row){
echo "<i>".$row."</i><br />";
}
PS: It's working but need to use trim() function for taken file names from .txt file
If the file content is always the same take the first row and use substr($str, 0, 7); // Outputs: SampleName123

Append multikey Json array in php?

I am working on a simple API for a web server where you can set answers to querys with multiple querys tied to one answer.
Here is my code so far but I need a way to append queries (multikeys) to each question (value) and I'm not sure how to fit it together.
$question = urldecode($_GET["q"]);
$admin = urldecode($_GET["admin"]);
$answer = urldecode($_GET["answer"]);
$donext = urldecode($_GET["donext"]);
if ($admin == "password123") {
$file = fopen("program.json", "a+") or die ("file not found");
$json = file_get_contents('program.json');
$data = json_decode($json, true);
$keys = array($q1, $q2, $q3); // need to append this with $q each time.
$train = array_fill_keys($keys, '$a."+".$donext');
//$data[$tagid] = $tagvalue;
$newjson = json_encode($data);
file_put_contents('program.json', $newjson);
fclose($file);
} else {
$file = fopen("program.json", "a+") or die ("file not found");
$json = file_get_contents('program.json');
$data = json_decode($json, true);
$a = $data->$q;
$piece = explode('+', $a);
$reply = $piece[0];
$nextcontext = $piece[1];
fclose($file);
echo $reply;
echo $donext;
}
How to put multiple keys to the same value:
<?php
$questionkeys = array('hi','hey','yo');
$answervalue = "hello to you too";
$outputarray = array_fill_keys($questionkeys, $answervalue);
echo $outputarray;
?>

PHP Parsing file into Array of Array

I have a file with many rows,each row have the following format:
1519382994.85#MSG#Something went wrong
So, for each row i have three field divided by #. A number, a message type and a string.
Now i want to read the file and split the contents.
I made it in this way:
//Opening the logger file
$myfile = file_get_contents("operations.txt", "r") or die("Unable to open file!");
$rows = explode("\n", $myfile);
$num_rows = count($rows);
$fieldList = array();
//Parsing rows using '#'
foreach ($rows as $row => $data) {
$row_data = explode('#', $data);
array_push($fieldList, (string)$row_data[0]);
array_push($fieldList, (string)$row_data[1]);
array_push($fieldList, (string)$row_data[2]);
}
The code is working well but i'd like to have an array of array and this kind of data:
0: Array [ "112323.76", "MSG", "Hello"]
1: Array [ "453435.78", "MSG", "Bye"] etc..
I tryed with this code but i'm doing something wrong.
$last=0;
$result = array();
for ($i = 0; $i < $num_rows; $i++) {
array_push($result, (string) $fieldList[$last], (string) $fieldList[$last+1],(string) $fieldList[$last+2]);
//echo $fieldList[$last].'<br>';
//echo $fieldList[$last+1].'<br>';
//echo $fieldList[$last+2].'<br>';
$last=$last+3;
}
I'm a newbie in PHP someone can help me please and tell me what i'm doing wrong? Tanx a Lot for your time
You could probably make use of the built-in fgetcsv:
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]]] )
This could look like:
$rows = [];
if (false !== ($handle = fopen("path/to/file", "r")))
{
while (false !== ($row = fgetcsv($handle, 1000, ",")))
{
array_push($rows, $row);
}
fclose($handle);
}
Don't know if it would be a lot faster, but looks a lot easier to me. The main benefits of this over file() and explode() are:
There is no need to have the entire file in RAM at once, processing could be done one row at a time.
it is easy to support other "Character Seperated Values" type files where fields may be quoted ($enclosure)
Just needed some modifications in your code. Added comments to modified lines-
$myfile = file_get_contents("operations.txt", "r") or die("Unable to open file!");
$rows = explode("\n", $myfile);
$num_rows = count($rows);
$finalFieldList = array(); // new array
//Parsing rows using '#'
foreach ($rows as $row => $data) {
$fieldList = array(); // temporary array
$row_data = explode('#', $data);
array_push($fieldList, (string)$row_data[0]);
array_push($fieldList, (string)$row_data[1]);
array_push($fieldList, (string)$row_data[2]);
array_push($finalFieldList, $fieldList); // it will push to final array containing all 3 values
}

Convert a CSV to JSON and change specific key values into Boolean or string using PHP

Is there a way I can change specific key values into boolean or string. The conversion changes all the Data into string. For example the Key value "Date" should be an integer instead of a string.
<?php
function csvToJson($fname) {
if (!($fp = fopen($fname, 'r') )) {
die("Can't open file");
}
$key = fgetcsv($fp, "1024", ",");
$json = array();
while ($row = fgetcsv($fp, "1024", ",")) {
$json[] = array_combine($key, $row);
}
fclose($fp);
foreach ( $json as $k=>$v ) {
$json[$k]['dateRequested'] = $json[$k]['DATE'];
$json[$k]['assignedAgent'] = $json[$k]['AGENT'];
$json[$k]['finalCompanyName'] = $json[$k]['COMPANY NAME'];
unset($json[$k]['DATE']);
unset($json[$k]['AGENT']);
unset($json[$k]['COMPANY NAME']);
}
return json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
?>
<?php
$json_data = csvToJson("lms.csv");
?>
Try this:
while ($row = fgetcsv($fp, "1024", ",")) {
// here $row contains all the columns in it in a numeric array
// Means 0 => first column of csv, 2 => second column of csv and so on
// you can convert any specific column value like
$json[] = array($row[0], setype($row[0], "string"), and so on);
}
You can do like this:
$json[$k]['dateRequested'] = (int)($json[$k]['DATE']);
$json[$k]['assignedAgent'] = $json[$k]['AGENT'];
$json[$k]['finalCompanyName'] = $json[$k]['COMPANY NAME'];
Sample usage :
$int = (int)(123);
$bool = (bool)(1);
$string = (string)(1234);
var_dump($int);
var_dump($bool);
var_dump($string);

Reading a text file into an array with PHP - advise

Ive the following Code , a function take a list of usernames and put in them in array then execute function called function get_all_friends , Code works fine and no error , my question here how to adjust the code if ive bulk of usernames lets say like 10k ?
Like reading from file include all usernames name and put them in array using
$file_handle = fopen("users.txt")
please advise !
<?PHP
$user1 = "usernamehere";
$user2 = "usernamehere";
$user3 = "usernamehere";
$u[] = $user1;
$u[] = $user2;
$u[] = $user3;
function get_all_friends($users)
{
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET);
$list = array();
foreach($users as $user)
{
$result = $connection->get( 'friends/ids', array(
"screen_name"=> $user)
);
foreach($result->ids as $friend)
{
$list[] = $friend;
}
}
return $list;
}
//call the function
$result = get_all_friends($u);
foreach($result as $res)
{
$query = "INSERT INTO friends (userid, name, grade, flag) VALUES ($res, 'name', 100, 0 ) ";
mysql_query($query);
}
//to print the databse result
echo "row<br />";
$res = mysql_query("SELECT * FROM friends");
while ($row = mysql_fetch_assoc($res))
{
print_r($row);
}
?>
Something like the following should work (untested):
$filename = "users.txt";
$file_handle = fopen($filename, "r");
$contents = fread($file_handle, filesize($filename));
$usernames = preg_split("/ (,|\\n) /", $contents);
fclose($file_handle);
The usernames must be separated by a comma or a new line.
Although, if you are positive that the usernames will only be separated by a new line OR a comma, this code will be faster:
$filename = "users.txt";
$file_handle = fopen($filename, "r");
$contents = fread($file_handle, filesize($filename));
// new line:
$usernames = explode("\n", $contents);
// or comma:
$usernames = explode(",", $contents);
fclose($handle);
Please choose only one of the $usernames definitions.
Specifically to answer the question, check file(..) - "Reads entire file into an array"
http://php.net/manual/en/function.file.php
Although you probably don't want to be doing it this way, if the file is large you'll be much better off reading sequentially or doing some sort of direct import.

Categories