Parsing a CSV file in PHP using regular expressions [duplicate] - php

This question already has answers here:
Regular expression for parsing CSV in PHP
(6 answers)
Closed 8 years ago.
I have a text file (similar to CSV concept) to parse and load into different columns.
I receive it from an external application I can't modify.
It uses ";" as field separator but unfortunatly we can have the same char also inside some content.
Here a little sample:
Code;Name;Address;E_mail;Contact name
000001;FUTURAMA SNC;VIA BARBAPAPA, 1;info#gmail.com;matteo futuro;
000006;FERRANTIBUS SRL;VIA TOPOLINO, 1;amministrazione#gmail.com;nicola ferri;
000008;MORMORO SPA;VIA CICCETTI, 30;"cri#mormoro.it; rossi#mormoro.it";panebianco gianpietro;
we use this code to parse the file
$file = fopen("C:\\wamp\\www\\testcsv\\customers.csv","r");
$result ="";
$i=0;
while(! feof($file))
{
$result[$i++]= fgets($file);
}
for($j=1;$j<count($result);$j++){
$tempData = preg_split("/[;]/",$result[$j]);
print_r( $tempData );
}
as you can see, in the last line of the sample file, we have ";" char inside email field.... so it is read as another column separator and in the third record the email field is splitted as 2 column, with the result I have an additional column.
Is there any way, using regular expression to skip ; char if it is inside the "" chars?
Thanks in advance for the help

You should not use regexpr to parse CSV files.
Use native PHP function http://php.net/manual/en/function.fgetcsv.php
This will solve your problem.

Related

PHP - Upload xml file with special characters in file [duplicate]

This question already has answers here:
How to parse XML with unescaped ampersand
(2 answers)
Closed 2 years ago.
I am trying upload xml file using simplexml_load_file but when in file is special character i'm getting an error ( There is everything alright without special character in it).
First of all, I am using XML file from another program so i can't change it.
This is sample of xml:
<wuo>
<header>
<title>title1</title>
</header>
<body>
<lp>1</lp>
<sign>124.455</sign>
<text>sample text with & character</text> //<-- this is causing the problem
</body>
<body>
<lp>2</lp>
<sign>12556.455</sign>
<text>sample text 2</text>
</body>
</wuo>
My code:
if(isset($_POST["submit"]))
{
if(isset($_FILES['wuo']) && ($_FILES['wuo']['error'] == UPLOAD_ERR_OK))
{
if(!simplexml_load_file($_FILES['wuo']['tmp_name']))
{
// if file has special character in it this fires up
echo 'Error';
}
else
$file = simplexml_load_file($_FILES['wuo']['tmp_name']);
print_r($file);
/**
showing file to html etc... unimportant code for this case
**/
}
else
echo 'Error:' . $_FILES['wuo']['error'];
}
I know, I should do something before simplexml_load_file but i don't know what exaclty. Or maybe I should use something else...
Btw: I don't need to secure it because this is only for me.
Your XML is not valid. An ampersand must be escaped as &.
If you can't change it yourself, you will need to pre-process it in some way before passing it to an XML parser.

Reading a text file with specific code tag information in php

I would like to read a file, generally a text file, each record is starting with a with a specific code (filed name) in the line and ended by another specific code for a complete record. Each specific code is delimited by character ^ as its value in php into dump into sql database.
text file e.g.
001^UK2000009
008^S54/01/R/M/X,
009^Male
110^text1
200^text2
001^UK2000008
008^S54/012/R/M/X
009^Female
110^text1a
200^text2a
and so on...
This is similar to php constructor File_MARC
thanks in advance
First you have to read a file with file methods in php and than you can get a specific column name and it's value by below way
First read a single line from a file and than use a explode method to break that line into different elements with space delimitation.
$columns = explode(' ', $line_variable);
After generating columns I can see that each key values are delimited by ^ (cap) symbol so for that also we can use the explode method.
$newColumn =[];
foreach($columns as $column){
$splited = explode('^', $column);
$newColumn[][$splited[0]] = $splited[1];
}
print_r($newColumn);
This is just to give you an idea that how you can achieve your task but rest is completely dependent on you.

How to read a txt file with php and replace certain variables? [duplicate]

This question already has answers here:
Python: Placeholder variables in text file
(2 answers)
Closed 2 years ago.
I am trying to open, read, and render the contents of a .txt file using PHP.
I want to replace all the new lines, \n, with a <br>. I could echo it inside of a <pre> tag, but when I tried this method, the page was no longer responsive.
I also want to replace wherever it says { name } or $name with a different variable, like how python fstrings work.
I currently have this:
echo file_get_contents("file.txt");
which will produce something that looks like this:
Line1, Line2, Line3, Line4 { Person1 }
How would I made the result look like this
Line1,
Line2,
Line3,
Line4 James
NO, it is not possible to treat it as f-string because there is no builtin function to evaluate an f-string. However, you may format the content with str.format method. Like:
name = 'Person Name'
readFile = input('Txt File: ')
file = open(readFile, 'r')
content = file.read()
print(content.format(**locals()))
file.close()
Hello Person Name
line 2

create PHP array using fopen with append [duplicate]

This question already has answers here:
PHP Array saved to Text file
(4 answers)
Writing Array to File in php And getting the data
(5 answers)
How do I store an array in a file to access as an array later with PHP?
(8 answers)
Closed 3 months ago.
I am having trouble figuring out how to write to a file using fopen "a" append mode.
the file itself is a simple PHP array:
$array = array(
"entry1" => "blah blah",
"entry2" => "forbarbaz",
);
simple enough. So using fopen with the 2nd arg set to "a" should allow me to append the file using fputs.... the problem is the opening and closing lines, ie $array = array( and );
so now the file should look like this:
"entry1" => "blah blah",
"entry2" => "forbarbaz",
how would I rebuild this data into a working PHP array assuming it is just a txt file with a list of entries without the opening and closing lines? Sorry if this is not clear, its a little complicated. No I am not going to store these values in a DB, I need the speed advantage by holding these particular values in a file array.
So the questions really is how would i go about constructing the usable PHP array from a txt file with a line by line list like this?
To clarify:
how do i pull in a txt file with lines like this:
"entry1" => "blah blah",
"entry2" => "forbarbaz",
and have a workable $php_array()????
Try this.
File format (at the beginning of work with it):
<?php
$array = array();
Now it's correct php-file.
Then simply add new rows like as follows:
$f = fopen('myarray.php', 'a');
fputs($f, PHP_EOL.'$array["entry1"] = "value1";');
fclose($f);
And use it by simply include('myarray.php');
Why not json_encode the array when you store it in the file and then json_decode the JSON into an array when you extract it from the file?
json_encode
json_decode
Maybe you're looking for the fseek function: http://se.php.net/fseek
When opening a file in r+ mode, the file pointer is at the beginning of the file. Sounds like you want to place it at the end of the file minus a few bytes, then write your new data.
Untested. Try this:
$data = file_get_contents('./data.txt', true);
$array = eval("array(".$data.")");

PHP: lookup for string in tags and embed it to another tag [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
A simple program to CRUD node and node values of xml file
I have a string (for example $output) with html code containing multiple tags and text. I need to lookup for all ID tags:
<id>123456</id>
and change them to:
<id>123456</id><url>www.webpage.com/somepage.php?id=123456</url>
As you can see the new tag is created and added after ID tag.
Webpage url address is stored in string $url_adr. ID number is always different in each ID tag. And there is multiple ID tags in string, so it needs to be changed one by one
I need this code in PHP. Thanks a lot....
In simple cases like this, you can do it with a regular expression replace:
$output = '<id>123456</id>';
$url_adr = 'www.webpage.com/somepage.php?id=';
preg_replace('~<id>(.*?)</id>~i', '<id>$1</id><url>'.$url_adr.'$1</url>', $output);
But if you need anything more complicated or full featured, you'd better take a look at proper XML parsers.

Categories