I have one text file in directory. I want to get contents of that text file.
in my text file
student&class&mark&grade
I am trying to my code here.
$myfile = "data.txt" ;
$getdata = file($myfile) ;
print_r($getdata) ; // student&class&mark&grade // working fine.
I'm trying to explode function
$arr = explode('&',$getdata);
print_r($arr); // not working
how to solve this problem ?
file() function return the data in array - file function
file_get_contents() return the data in string form
Try file_get_contents() - file_get_contents
$myfile = "data.txt" ;
$getdata = file_get_contents($myfile) ;
$arr = explode('&',$getdata);
print_r($arr); // Will work
file() returns an array of the lines of the file, so this is the main problem. You will also find that file() will, by default, include a new line on the end of each line - which you probably don't want.
This code uses array_walk() to process each line, using explode() on a line at a time, replacing the original line with the array.
$getdata = file($myfile, FILE_IGNORE_NEW_LINES);
array_walk ( $getdata, function ( &$data ) { $data = explode("&", $data);});
print_r($getdata);
This outputs...
Array
(
[0] => Array
(
[0] => student
[1] => class
[2] => mark
[3] => grade
)
)
Related
OK, this seems rather simple and I've looked for another answer, but perhaps I'm not searching for the right thing. I have a list of URLs and pages containing those URLS
https://example.com/?p=1 | https://example.com/go/test404/
https://example.com/?p=1 | https://example.com/404
https://example.com/?p=5 | https://example.com/go/test404/
https://example.com/?p=5 | https://example.com
I loop through each line and parse the URLs into $parent (the first column) and $destination (second column).
Now, I want to end up with the following, but can't figure out how to generate this structure, with the outer array called $allLinks:
Array
(
[https://example.com/go/test404/] => Array
(
[0] => https://example.com/?p=1
[1] => https://example.com/?p=5
)
[https://example.com/404] => Array
(
[0] => https://example.com/?p=1
)
[https://example.com] => Array
(
[0] => https://example.com/?p=5
)
)
Thank you very much for assistance in this.
In a loop, I've tried $allLinks[$destination] .= [$parent] and array_push($allLinks[$destination], $parent) but neither seem to be working for me.
You can do this as you are reading/separating the parts. I don't know how you're doing that, but the below assumes you have read lines from a file into an array. Just use the parent as the key and append [] each destination to the array:
foreach($file as $line) {
list($parent, $destination) = explode(' | ', $line);
$result[$parent][] = $destination;
}
That is how I would do it, but rereading it seems you want the opposite:
foreach($file as $line) {
list($parent, $destination) = explode(' | ', $line);
$result[$destination][] = $parent;
}
array_push requires an array as the first argument, so to use it (not recommended) you'd have to check if it is set and if not then define it as an array first. Something like:
$result[$destination] = $result[$destination] ?? [];
array_push($result[$destination], $parent);
The top line translates into:
if(!isset($result[$destination])) {
$result[$destination] = [];
}
Recently I was practicing problems in Hackearth and I was unable to scan tab-separated values.
Ex(Inputs): 12 3 6 1
The input is treated as a file, it seems, because fscanf is used to read it.
I was trying to scan it using while loop like this:
$arr = [];
$i = 0;
while($i < 4){
fscanf(STDIN, "%s\t", $a);
$arr[] = $a;
$i++;
}
But when I am printing $arr like:
print_r($arr);
It shows like this:
Array
(
[0] => 12
[1] => 12
[2] => 12
[3] => 12
)
I checked this problem but unable to solve my problem.
How can I scan all the numbers using a loop and put it in an array?
According to the documentation:
Each call to fscanf() reads one line from the file.
So you can't call fscanf() in a loop to read each number from the same line. The second iteration tries to read the next line, but there isn't one.
You can use fgets() to read a whole line, then use explode() to split it into an array at the delimiters:
$line = fgets(STDIN);
$line = rtrim($line); // remove the newline
$arr = explode("\t", $line);
Or use fgetcsv() to do this in one step:
$arr = fgetcsv(STDIN, 0, "\t");
I am using an API that returns a CSV string as the following:
Date,Open,High,Low,Close,Volume,Adj Close 2014-06-13,3.10,3.30,3.10,3.30,6638300,3.30
I was wondering if there is an easy way to convert this CSV string to an associative array? I am familiar with working with a CSV file, but not sure what to do with a CSV file string response. I am trying to avoid writing the response to a file, just so I can read it back.
Note, writing this response to a CSV file would result in two rows and seven columns.
If the line terminator is \r\n, then first you need to explode them thru that. Then you can proces from there. Consider this example:
$data = explode("\r\n", $csv_string);
// get the headers first
$headers = array_map('trim', explode(',', array_shift($data)));
$new_data = array();
// get the values and use array combine to use the headers as keys for associative array
foreach($data as $values) {
$pieces = explode(',', $values);
// i just assigned it in an array, since we dont know how many lines of data you will receive
$new_data[] = array_combine($headers, $pieces);
}
$new_data should yield something like this:
Array
(
[0] => Array
(
[Date] => 2014-06-13
[Open] => 3.10
[High] => 3.30
[Low] => 3.10
[Close] => 3.30
[Volume] => 6638300
[Adj Close] => 3.30
)
)
Or just the usual way of handling csv strings. Use str_getcsv().
$data = str_getcsv($csv_string, "\r\n");
$headers = explode(',', array_shift($data));
$data = array_combine($headers, explode(',',reset($data)));
As others have mentioned, str_getcsv() is your friend and is an easy method to convert a CSV string into an array. This function will return an array of results. If you'd like to make it an associative array, use array_combine().
Honestly, though -- str_getcsv() may be overkill. Consider this method using explode():
// so given this string returned by the API
$api_s = "Date,Open,High,Low,Close,Volume,Adj Close\r\n2014-06-13,3.10,3.30,3.10,3.30,6638300,3.30";
// split on carriage return & line feed into two strings
$api_r = explode("\r\n", $api_s);
// split keys and values by comma
$keys = explode(',', $api_r[0]);
$vals = explode(',', $api_r[1]);
// construct associative array
$my_assoc_r = array_combine($keys, $vals);
Lets say I have 2 arrays .
$arr1=array("foo"=>"bar", 1=>"one", 2=>"two");
$arr2=array("h"=>"eich", 3=>"three", 4=>"four");
By using file_put_contents I am able to print the array into a new php file something like this :
<?php
$arr1 = Array
(
"foo"=>"bar",
1=>"one",
2=>"two"
) //need a semicolon here
$arr2 = Array
(
"h"=>"eich",
3=>"three",
4=>"four"
)//need a semicolon here
My question is , How can I get a semicolon after the end of each array ?
Because you even have this problem, I guess you are looping the arrays to convert them to PHP code and not using var_export() - which you should be:
$arr1 = array("foo"=>"bar", 1=>"one", 2=>"two");
$arr2 = array("h"=>"eich", 3=>"three", 4=>"four");
$file = "<?php\n\n".var_export($arr1, TRUE).";\n\n".var_export($arr2, TRUE).";\n";
file_put_contents('newfile.php', $file);
See it working
This question already has answers here:
How create an array from the output of an array printed with print_r?
(11 answers)
Closed 10 years ago.
How can i create variable from it's print_r output ? In other words, i'd like to know if something similar to my fictive var_import function exists in php ? var_import would be the inverse of var_export
He is a use case:
$a = var_import('Array ( [0] => foo [1] => bar )');
$output = var_export($a);
echo $output; // Array ( [0] => foo [1] => bar )
If such a function does not exist, is there a tool (or online tool) to do this ?
I am also interested to do the same with var_dump output.
EDIT: The variable is only available as a print_r output (string). To clarify what i need, imagine the folowing situation: someone posts a some sample on the internet somewhere with a print_r output. To test his code, you need to import his print_r variable into your code. This is an example where var_import would be usefull.
Amusingly the PHP manual contains an example that tries to recreate the original structure from the print_r output:
print_r_reverse()
http://www.php.net/manual/en/function.print-r.php#93529
However it does depend on whitespace being preserved. So you would need the actual HTML content, not the rendered text to pipe it back in.
Also it doesn't look like it could understand anything but arrays, and does not descend. That would be incredibly difficult as there is no real termination marker for strings, which can both contain newlines and ) or even [0] and => which could be mistaken for print_r delimiters. Correctly reparsing the print_r structure would be near impossible even with a recursive regex (and an actual parser) - it could only be accomplished by guesswork splitting like in the code linked above.. (There are two more versions there, maybe you have to try them through to find a match for your specific case.)
Why don't you use var_export instead ?
var_export(array(1, 2, 3)); // array(1, 2, 3)
You can import var_export's output with eval(), however I would recommend you to avoid this function as much as possible.
The following functions are better for exporting and importing variables:
serialize() and unserialize():
$string = serialize(array(1, 2, 3));
$array = unserialize($string); // array(1, 2, 3);
Or json_encode() and json_decode():
$string = json_encode(array(1, 2, 3));
$array = json_decode($string);
You can wrap it in an output buffer:
ob_start();
print_r(array(1,2,3));
$arr = ob_get_clean();
echo $arr;
Ok so I misunderstood the first question. I think I have another solution which actually does answer your question:
<?php
$ar = array('foo','bar');
$p = print_r($ar, true);
$reg = '/\[([0-9]+)\] \=\> ([a-z]+)/';
$m = preg_match_all($reg, $p, $ms);
$new_ar = $ms[2];
echo "Your wanted result:\n";
print_r($new_ar);
If you want to import a var_export()'s variable, you can run the eval() function.
Or if you save the contents into a file (with a return statement), you can use the return value of include() or require().
But I would rather use serialize() and unserialize() or json_encode() and json_decode().
define('EXPORT_JSON', 1);
define('EXPORT_SERIALIZE', 2);
function exportIntoFile($var, $filename, $method=EXPORT_JSON)
{
if ( $method & EXPORT_JSON )
file_put_contents( $filename, json_encode($var) );
else if ($method & EXPORT_SERIALIZE)
file_put_contents( $filename, serialize($var) );
}
function importFromFile($filename, $method=EXPORT_JSON)
{
if ( $method & EXPORT_JSON )
return json_decode( file_get_contents($filename) );
else if ($method & EXPORT_SERIALIZE)
return unserialize( file_get_contents($filename) );
}
I'm not good at regex to code the final trash removal. Here is how far I could get though:
$str = 'Array ( [0] => foo [1] => bar [2] => baz)';
$t1 = explode('(', $str);
$t2 = explode(')', $t1[1]);
$t3 = explode(' => ', $t2[0]);
unset($t3[0]);
print_r($t3);
output:
Array
(
[1] => foo [1]
[2] => bar [2]
[3] => baz
)