PHP and file manipulation - php

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
}

Related

php read csv data as a string

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.

Can't find newline in csv string

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.

Read a csv file and create another csv file using php

I have a .csv file and when I open it via notepad it looks like:
ID501501503502
And when I print it in the browser via php, it looks like
ID 501 501 503 502
My code is:
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0);
$fh = fopen('php://output', 'w');
if (! empty($data)) {
foreach ($data as $item) {
echo $item."<br>";
//fputcsv($fh, array($item));
}
}
So basically the br tag inside the for loop doesn't work.This is my first problem.
And the second problem is even if I use fputcsv(now it is turned off) it doesn't create a actual csv file.
Now my question is how come it has got no space in notepad and when I print in browser it gets space?
I have only one column and nothing else.
Any help is highly appreciated. Thanks in advance.
As mentioned in my comment, it looks like your original file is saved with UNIX line endings, and then you're using fgetcsv in Windows, so the whole file is being read as one line. There's probably one <br> at the end of the whole output.
So before processing your file, you'll need to preprocess it to convert the line endings.
On Linux, the utility unix2dos does what you want. Or, you can simply replace \n with \r\n in your file.
The other problem is that fgetcsv does not turn an entire file into an array. Instead, it reads a single line from your file handle, and converts that to an array. You'll need to read lines inside a loop:
while (($data = fgetcsv($handle)) !== FALSE) {
// $data contains one line of the CSV, in array form
// now you can fputcsv the single line
}

How to add additional text to file php

This is my code:
$open = fopen('emails.txt', 'w+');
if ($open) {
$content = "$first $last <$email>,";
if (fwrite($open, $content)) {
// ...
}
}
However, when I run this, it just replaces the text I already have in the file. How do I just add to the file, instead of replacing it?
You have to open the file in append mode, by passing a as the second parameter to fopen():
$open = fopen("emails.txt", 'a');
Then, data you write to the file will be appended to the end of the file, preserving data that was previously written to the file.
If you're only appending one block of text into the file at every request, you could look into file_put_contents() as well:
file_put_contents('emails.txt', $content, FILE_APPEND);
Shorter than having to write fopen(), fwrite() and fclose(), though the latter is more or less optional :)

How to parse file in php and generate insert statements for mysql?

In case of csv file we have fgetcsv in php to parse and get the output but in my case file is .dat and I need to parse it and store it into MySQL Database and so do we have any built in function in php like fgetcsv that can work in similar fashion on .dat file ?
Here is the sample value, it has headers DF_PARTY_ID;DF_PARTY_CODE;DF_CONNECTION_ID and its value as mentioned under.
Sample Data:
DF_PARTY_ID;DF_PARTY_CODE;DF_CONNECTION_ID
87961526;4002524;13575326
87966204;4007202;13564782
What's wrong with fgetcsv()? The extension on the file is irrelevant as long as the format of the data is consistent across all of your files.
Example:
$fh = fopen('example.dat', 'r');
while (!feof($fh)) {
var_dump(fgetcsv($fh, 0, ';'));
}
Alternatively, with PHP5.3 you can also do:
$lines = file('example.dat');
foreach($lines as $line) {
var_dump(str_getcsv(trim($line), 0, ';'));
}
IMHO .dat files can be of different formats. Blindly following the extension can be error-prone. If however you have a file from some specific application, maybe tell us what this app is. Chances are there are some parsing libraries or routines.
I would imagine it would be easier to write a short function using fopen, fread, and fclose to parse it yourself. Read each line, explode to an array, and store them as you wish.

Categories