php fgets explode shows "Array." instead of $array [duplicate] - php

This question already has answers here:
How to echo out the values of this array?
(5 answers)
Closed 8 years ago.
I am trying to convert a plain text logfile (no wordwrap) into something more readable.
php-file
<?php
$log = fopen("/home/raspi/scripts/logs/test.log", "r");
while (!feof($log)){
$arrM = explode("|",fgets($log));
echo "$arrM . <br>";
}
fclose($log)
?>
Whenever there is a | in the logfile the php script should change it to <br> in the output.
However, when opening the php file, all I get is
Array .
Array .
Content of the logfile
Sachen|Enter|nochmal Enter|Und schon wieder Enter. I am a beginner and started reading about fopen and explode. Thought this would be just what I needed but something is wrong...? Thanks in advance :)

The problem is that you can't output an array with echo, you'd need to loop like
foreach ($arrM as $row) echo $row; or use var_dump($arrM) for 'developer-output' or print_r($arrM) alternatively.

use print_r() for print array (developer-output)
<?php
$log = fopen("/home/raspi/scripts/logs/test.log", "r");
while (!feof($log)){
$arrM = explode("|",fgets($log));
//echo "$arrM . <br>";
print_r($arrM);
}
fclose($log)
?>
echo print one or more strings
<?php
$log = fopen("/home/raspi/scripts/logs/test.log", "r");
while (!feof($log)){
$arrM = explode("|",fgets($log));
//echo "$arrM . <br>";
foreach($arrM as $string){
echo $string . '<br>';
}
}
fclose($log)
?>

use echo "<pre>";print_r($arrM);
Reason , if an array is printed in echo , PHP will show you Array, so you better have a look whats coming thru print_r and accordingly you can access variable ,or put it in loop.

Related

How Do I Write An Array To A File PHP? [duplicate]

This question already has answers here:
Print array to a file
(14 answers)
How do I store an array in a file to access as an array later with PHP?
(8 answers)
Closed 8 months ago.
I am trying to write an array to a file in php. If I do
$var = "Var";
fwrite($file, "<?php \$var = '$var';");
and I echo $var in the new file it will return "Var". But if I do the same thing with an array it will return "Array". How can I fix this?
The var_export() function does exactly what you want: it outputs a variable in a way it can be used in a .php file. Please note that when using var_export, you should drop the quotes around your variable in the output string.
fwrite($file, "<?php \$var = ".var_export($var, true).";");
You need to turn the array into a string that is separated by a comma. This is one of those problems where you will run into lots of edge cases. For instance, the below code will fail if one of the elements in the array contains a ' single quote character.
<?php
$hello = 'Hello';
$world = 'World';
$integer = 100;
$array = [
$hello,
$world,
$integer
];
function add_quotes($e) {
if (is_string($e))
return sprintf("'%s'", $e);
else
return $e;
}
$php_string = '<?php
$array = [';
$php_string .= implode(',', array_map('add_quotes', $array));
$php_string .= '];';
$fp = fopen('output.php', 'w');
fwrite($fp, $php_string);
This will output
<?php
$array = ['Hello','World',100];
How you fix things depends very much on what you want to do with the stored data.
The simple example is to write each element separately:
<?php
$arr = ['Apple','Orange','Lemon'];
$fh = fopen('myFile.csv', 'w');
foreach($arr as $el) {
fwrite ($fh, "$el\n"); // add a new line after each element to delimit them
}
fclose($fh);
You could create a CSV file with fputcsv():
<?php
$arr = ['Apple','Orange','Lemon'];
$fh = fopen('myFile.csv', 'w');
fputcsv($fh, $arr);
fclose($fh);
You could write JSON data:
<?php
$arr = ['Apple','Orange','Lemon'];
file_put_contents('myFile.json', json_encode($arr));
If you're feeling bold you could create an XML file (no snippet for this one, but trust me, it can be done).
You could write serialized PHP data (see serialize()) - not recommended.
Or you could create your own format for your specific application.

I am trying to turn an array into string, php is confounding me though?

Hi I am trying to write a piece of code that will allow me to read from an array and then output the required text as string
The code in question:
$mytext = (string)$output[0];
$breakup = explode('--', $mytext);
echo "###########################################";
echo $breakup;
This is the first time I've tried doing this and I don't think implode would work.
Could someone shed some light on what I am doing wrong or help me reach an answer?
try something like this:
$myString = "bob-fred-john-sarah-claire-julie-lisa";
$ex = explode("-", $myString);
then to see whats in the $ex array you can print it out like this:
echo "<pre>";
print_r($ex);
echo "</pre>";
to access individual values of the array you use the array index like this (remember arrays start at index 0):
echo $ex[0]; //this will echo bob.
echo $ex[1]; //this will echo fred.
to echo out each part of the $ex array you use something like a foreach loop:
foreach($ex as $index => $value){
echo $value."<br>";
}
To print out the contents of the array individually you can do it this way:
$mytext = (string)$output[0];
$breakup = explode('--', $mytext);
echo "###########################################";
for ($i=0; $i<count($breakup); $i++) {
echo $breakup[$i];
}
An alternative way is with foreach:
foreach ($breakup as $value) {
echo $value;
}
As mentioned by others, print_r can be used for displaying an array in easily readable format:
print_r($breakup);
You can also use it to store a string:
$myvalue = print_r($breakup, true); //note the ,true which will return the value instead of printing it.

need to access 3 values in a php array that contains 20, is a 3d array and I need to access the same values 60 times

<?php
// Open the file
$filename = 'pvemail.txt';
$fp = fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
//print_r ($array);
for ($c = 0; $c < count($array); $c++){
$cell = explode(",", $array[$c]);
print_r ($cell);
echo '<br/>';
}
?>
I am currently working on this code. I have taken a text file generated from a Google report, and managed to explode it into an array, and then I've taken each element of the array and exploded that into another array. However, the problem I'm now having is I only want to retrieve 3 elements of the second exploded array and there are 20 elements to each array.
What would be the best way to go about this, should I use a for or foreach loop? I only need to print $cell[2], $cell[11] and $cell[12]. I have tried using:
echo ($cell[2] + " " + $cell[12] + " " + $cell[11]
($cell[11] and $cell[12] are in this order because 11 is a last name and 12 is a first name and I want the first name first so I've had to put them backwards) but when I run that piece of code it just outputs line breaks and 0's. I'm really just wondering what would be the most effective method of looping through the arrays, and should I do it within the loop that I have already established?
I was thinking that if I were to put it inside my existing for loop I could use an if/else loop, something like:
if($cell = $cell[2]){
echo ($cell[2])
};
but i'm not convinced this will work. Should I define a variable to store $cell[2], [11] and [12] in, and create my if loop based on that, and then I would only need to echo the variable? Is that likely to be effective? Any help would be appreciated, I've looked around on the forum for posts similar to this but I haven't been able to find anything.
20130912,b875c9b154cf7b8d,el#pv-eu.com,ACTIVE,30720,1054180015,,,20100902,‌​20130910,20130904,L,E,,,,20130911,2010-09-02 09:11:37,2013-09-10 23:51:21,2013-09-04 03:06:09,2013-09-11 00:41:24
20130912,66c63753b8188f17,lf#pv-eu.com,ACTIVE,30720,3699701524,,,20110315,201309‌​11,20130911,F,L,,,,19691231,2011-03-15 02:00:31,2013-09-11 00:50:17,2013-09-11 00:52:16,1969-12-31 16:00:00
20130912,bd5ef40689adf9ac,ah#pv-eu.com,ACTIVE,30720,3476851137,,,20110426,201309‌​11,20130910,H,A,,,,20110720,2011-04-26 01:47:56,2013-09-11 16:58:48,2013-09-10 06:20:26,2011-07-20
This is how the text file itself looks, although there is a lot more data. All I'm trying to pull is the email address and name.
Assuming pvemail.txt is a CSV file, does this solve your problem?
$content = file_get_contents('pvemail.txt');
$lines = explode("\n", $content);
header('Content-type: text/plain');
foreach($lines as $line) {
$values = explode(',', $line);
echo $values[2], ' ', $values[12], ' ', $values[11], "\n";
}
Using the 3 sample lines, the above code outputs this:
el#pv-eu.com E L
lf#pv-eu.com L F
ah#pv-eu.com A H

Understand PHP arrays

I'm a newbie and I have a very basic question about PHP arrays
Code:
While(!feof($file_handle))
{
$SecondRow = fgets($file_handle); //gets row
$trimmed = trim($SecondRow); //removes extra bits
$replace = array("'");
$finalstring = str_replace($replace, "_", $trimmed); //Still a string w/o "'"'s
$CleanString = preg_split("/[\s]*[,][\s]*/", $finalstring); //creates the array
//print_r($CleanString);
echo "Row " . $CleanString[1]. "<br/>"; //??????
.....
}//end while
the opened file has the following:
0001,sparta
0005,PURCHASING
...
...
...
Question:
When I echo "Row " . $array[0], I get the first column as expected. But when I echo "Row " . $array[1], I get an the "Undefined offset: 1" error. When the string is read into the array (via preg_split) aren't both
array[0]->0001 and array[1]->sparta set?
thanks.
Looking at your entire code, you're essentially replicating a native function like fgetcsv() or one of it's equivalents.
Just pick one and be done :)
As far as determining how to use the array, as noted in the comments use print_r or var_dump() to guide you. Also read up on PHP Arrays
This is because fgets() get one row at time (one row per "loop").

accessing text files using php?

i was wondering how i can use php to access text files and display the information using php arrays, this might seem like a newbie question, but i havent worked with external files.
so here goes.
home.txt:
ha15rs,250,home2.gif,2
ha36gs,150,home3.gif,1
ha27se,300,home4.gif,4
ha4678,200,home5.gif,5
what i wanted to do is sort this information in a html table, with each line as a row and 4 coloumns to represent the data!! thanks cheers :))
Looks like comma separated values. See the examples at http://ee.php.net/manual/en/function.fgetcsv.php
you can do something like that :
<?php
$file = file_get_content('file.txt');
$array = explode("\n", $file);
Notice that it depend of your newline type :
typically:
Gnu/Linux / Unix / MacOS since X use "\n"
Windows use "\r\n"
MacOS before X use "\r"
you should look at the file() function too, it reads the file into an array line by line.
after that you can seperate the values with explode().
<?php
$foo = file('example.txt');
// will echo the 2nd line of the example.txt-file
echo $foo[1];
// echos all items seperated by a comma
foreach($foo as $line=>$values){
$value_arr = explode(',',$values);
echo 'line #'.$line.': ';
foreach($value_arr as $id=>$item){
echo $id.': '.$item.'; ';
}
echo "\n";
}
?>
a start of deal with this :
# echo before table headline
...........
$handle = #fopen("myfile.txt","r");
# read line by line
while (($buffer = fgets($handle, 4096)) !== false) {
echo '<tr>';
$array = explode(',', $buffer);
foreach($array as $val){
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}

Categories