Is there a function in php that lets you read a csv and return a string as it is.
I am aware of functions like fgetcsv etc that reads the csv and returns an array. But I was wondering if there is a way to get the full string as it is.
You must use the file_get_contents function
$data = file_get_contents('http://absoluteUrl');
or
$data = file_get_contents('local url');
Instead, to obtain an array of csv's lines use the file function.
You could use the file function:
$file = file("somefile.csv")
The you have every line in the variable file:
$file[0] = Firstline, aso.
Related
Using file_get_contents() I retrieve CSV data from an external URL. In this data there are breaks visible for every new record in the CSV. However, when I try to explode the lines, I only get one item in my array, containing the full CSV dataset. This is the code I use:
$data = file_get_contents('http://example.url/csvdata.asp?id=20'); // has 12 records
$rows = explode("\n", $data);
echo count($rows); // returns 1
Could this have to do with that an ASP script generates the CSV? Do they use other new line characters?
Use file and let PHP handle the new lines
file — Reads entire file into an array
You can simply do
$rows = file('http://example.url/csvdata.asp?id=20');
\n can work but there are more ways for new lines. This should work:
$lines = preg_split("/\\r\\n|\\r|\\n/", $data);
I had the same issue with mine. I found this somewhere on SO:
$rows = explode(PHP_EOL, $data);
PHP_EOL finds the end of the line.
if(isset($_POST['submit']))
{
$file = $_FILES['file']['name'];
$fh = fopen($file,'r+');
// string to put username and passwords
$users = '';
while(!feof($fh)) {
$user = explode(' ',fgets($fh));
foreach ($user as $value)
{
$number= rand(1000,10000);
$final_number[] = $value .','. $number;
}
}
//print_r($final_number);
file_put_contents($_FILES['file']['name'], $final_number);
}
this is my code for appending a random text to a string with comma and save it in text file but when i am saving it it is not saving properly after comma it is going to next line which should not happen plzz.. help me
Your code starts with a very big issue: you try to open and read from a file that, most probably, doesn't exist.
$file = $_FILES['file']['name'];
$fh = fopen($file,'r+');
As you can read in the documentation, assuming that your form contains an input element of type file having the name file, $_FILES['file']['name'] is the original name of the uploaded file, on the user's computer. It is only the name and it is not the name of the file on the server. It is provided just as a hint for the file's content (check the filename extension) but you cannot rely on it.
The content of the file is temporarily stored on the webserver in a file whose path can be found in $_FILES['file']['tmp_name']. You should pass it to the PHP function is_uploaded_file() to be sure the file was uploaded and your script is not the victim of an injection attempt then, if you need to keep it, use move_uploaded_file() to move it where you need. If you don't move it, when your script ends the temporary file is deleted.
Another problem of your code is on the lines:
$user = explode(' ',fgets($fh));
foreach ($user as $value)
As explained in the documentation, the function fgets() called without a second argument reads a line from the input file, including the newline character that ends it. Since you split the line into words I think you don't need the newline character. You can remove it by using trim() with the string returned by fgets() before passing it to explode().
The last issue of the code is:
file_put_contents($_FILES['file']['name'], $final_number);
Because $final_number is an array1, file_put_contents() joins its elements to get a string and writes the string into file. This operation concatenates the random value generated for a $value with the next $value and there is no way to tell which is which after the data is stored in the file. You probably need to keep them on separate lines. Use function implode() on $final_number, with "\n" as its first argument and write the generated string into the file instead.
The last one: don't write the generated content to $_FILES['file']['name']. It is not safe! It contains a string received from the browser; a malicious user can put whatever path they want there and your script will overwrite a file that it shouldn't change.
Create a directory dedicated to store files generated by your code and generate filenames based on an always incremented counter (the current time() or microtime() f.e.) for the files you store there. Never trust the data you receive from the browser.
1 $final_number is used as $final_number[] = ... and, because it is not defined when this line of code is executed for the first time, PHP creates an empty array for you and stores it in $final_number. Don't rely on this feature. Always initialize your variables before their first use. Put $final_number = array(); before the while().
I am going to use a different approach than you, let's say that the data you want to save to the file is stored in the variable $data.
So to append this data to the file with a comma at first, we can use just two lines of code:
$previousFileContent = file_get_contents("filename.txt");
file_put_contents("filename.txt", trim($previousFileContent . "," . $data));
I am using php to get the contents of a webpage:
$fileContent = file_get_contents('http://insertwebsitenamehere.com');
Is there a way to seek a line number andreturn the line at that location?
I know you can use SplFileObject::Seek if the fileContent is a file. Can I perform something similar without the need to turn it into a file?
You want file() instead
$fileContent = file('http://insertwebsitenamehere.com');
echo $fileContent[39]; //line 40
I need to create a CSV file from a PHP array, I'm aware of the fputcsv() function. I've a recollection that a better function exists for this kind of stuff but I can't find it nor remember it's name.
Does anyone know of such function or am I imagining?
I might be making some confusion with the fgetcsv() function and the str_getcsv() equivalent.
fputcsv is to write an array into a file with CSV format. fgetcsv is to read data from a file with CSV format and convert it into an array. And str_getcsv is to convert a string in CSV format into an array.
So fputcsv and fgetcsv are their respective inverses. And fgetcsv could be a function that uses str_getcsv.
I was wondering if it is possible to open an xml file as a plain text file so I can read in each line and manipulate the text?
$xml_file = '/var/www/file.xml';
$contents = file_get_contents($xml_file); // Dumps the entire file into a single string
$contents = file($xml_file); // Dumps each line into an array
However, I would recommend using simplexml_load_file() (even though you said you wanted to avoid it) because there is no guarantee as to how the xml will be formatted. It could all be on a single line or formatted with line-breaks in unexpected places.
Why not use any of the XML parser/manipulator directly?
You can find those references at http://www.php.net/manual/en/refs.xml.php
If you have a nicely formatted XML file then,
$file = 'file.xml';
// get contents and normalize the newline
$xml_arr = file($file);
foreach($xml_arr as &$line){
// do your manipulation to $line
}
$ctns = implode("\n",$xml_arr);
file_put_contents($file,$ctns); // write back
To read file as array of strings use file function:
$lines = file('your_xml_file.xml');
foreach($lines as $line) {
## do the stuff for each line
}