I really need some help on an issue: I'm converting an XML to CSV using a PHP script, but the XML contains some + signs and I don't know how to remove them from the CSV.
This is the XML file structure:
<PRICES>
<PRICE>
<WIC>HDE0AAFGRBOX</WIC>
<STOCK>100+</STOCK>
<MY_PRICE>219.00</MY_PRICE>
</PRICE>
</PRICES>
This is the script I use:
<?
$filexml='stock.xml';
if (file_exists($filexml)) {
$xml = simplexml_load_file($filexml);
$f = fopen('stock.csv', 'w')
foreach($xml->PRICES->PRICE as $price) {
fputcsv($f, get_object_vars($price),',','"');
}
fclose($f);
}
?>
The script works fine and the CSV file is good, but because I'm a noob with PHP I don't know how to remove the "+" sign.
Any help will be greatly appreciated.
Thanks in advance!
You could try to trim the chars you want to be removed (the '+' char):
foreach($xml->PRICES->PRICE as $price) {
$price->STOCK = trim($price->STOCK, "+");
fputcsv($f, get_object_vars($price),',','"');
}
Try to use str_replace :
$filexml='stock.xml';
if (file_exists($filexml)) {
$xml = simplexml_load_file($filexml);
$f = fopen('stock.csv', 'w')
foreach($xml->PRICES->PRICE as $price) {
$price->STOCK = str_replace("+","",$price->STOCK);
fputcsv($f, get_object_vars($price),',','"');
}
fclose($f);
}
Related
I am trying to replace some hyperlinks in a csv file, like this one:
[https://assets.suredone.com/683987/media-pics/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. Here is my code:][1]. Here is my code:
<?php
$in_file = 'gabriel-images-urls.csv';
$out_file = 'results.csv';
$fd = fopen($in_file, "r");
$new_array= array();
$toBoot= array();
while ($data = fgetcsv($fd)) {
echo '<pre>';
if (strpos($data[2],'media-pics') !== false) {
$data[2]=str_replace('media-pics','media-photos',$data[2]);
fputcsv($fd, $data);
// echo $output;
}
}
?>
The new link for example must look like this:[1]https://assets.suredone.com/683987/media-photos/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. The goal is he "media-pics" substring to be replaced with "media-photos". At this point nothing happens in the file. I think this is because the file is open only for reading but I am not sure.
Can you not simply do a string replacement on the whole file rather than attempting to load and process each line of the file using fgetcsv?
<?php
$srcfile='gabriel-images-urls.csv';
$outfile='results.csv';
$csvdata=file_get_contents( $srcfile );
$moddata=str_replace('media-pics','media-photos',$csvdata);
file_put_contents( $outfile, $moddata );
?>
I have a file (sites.txt) that has two entries:
http://www.url1.com/test1.xml
http://www.url2.com/test2
Whenever I execute the below PHP code, the 'url1.com' returns false, and the 'url2.com' is loaded into $xml. The odd part is that if I interchange the URLs in the file, i.e.
http://www.url2.com/test2
http://www.url1.com/test1.xml
It loads both. Both URLs are valid XML documents. Why does the order matter here?
Code:
if (file_exists('sites.txt')) {
$file_handle = fopen("sites.txt", "r");
while (!feof($file_handle)) {
$site = fgets($file_handle);
$xml[] = simplexml_load_file($site);
}
fclose($file_handle);
}
try changing your text file to a csv then explode contents of the file on the delimiter:
http://www.url1.com/test1.xml,
http://www.url2.com/test2
$file = fopen("sites.txt", "r");
$files = explode(",", $file);
Sounds like there are some other things going on in addition to this but that you may have that sorted out...
I've got a problem where I'm trying to read a text file like this:
Joe
Johnson
Linus
Tourvalds
and while parsing it in php, I need to be able to detect the newlines. I'm trying to correctly define $newline. I'm looping through the array of lines in the $file variable.
while($line = next($file))
if($line = $newline)
echo "new line";
The problem is that I can't seem to match the newline character. I know that it is actually showing up in the $file array, because this:
while($line = next($file))
echo $line;
outputs the file verbatim, with newlines and all. I've already tried "\n", " ", and I'm not sure what to try next. A little help?
$file = file("path/to/file.txt");
// Incase you need to call it multiple times ...
function isNewLine($line) {
return !strlen(trim($line));
}
foreach ($file as $line) {
if (isNewLine($line)) {
echo "new line<br/>";
}
}
Maybe something like this would work for you?
while($line = next($file)) {
if(in_array($line, array("\r", "\n", "\r\n"))) {
echo "new line";
}
}
I think this solution may help you guys. This works if you are parsing csv that is generated from Mac or windows. Reading csv with multilines created in Mac, gives problem i.e. you cannot read each line in a loop but all csv data is read as single line.
This problem is solved by following solution:
//My CSV contains only one column
$fileHandle = fopen("test.csv",'r');
$codesArray = array();
count = 0;
while (!feof($fileHandle) ) {
$line = fgetcsv($fileHandle);
if($line[0]!="") {
$data = str_replace("'", "", (nl2br ($line[0])));
$dataArray = explode('<br />' ,$data );
foreach($dataArray as $data) {
$codesArray[] = trim($data);
}
}
}
echo "<pre>";
print_r($codesArray);
data.txt
ha15rs,250,home2.gif,2
ha36gs,150,home3.gif,1
ha27se,300,home4.gif,4
ha4678,200,home5.gif,5
i want convert this textfile into xml using simplexml module using php? thanks :))
p.s. im new to this
EDIT:
<allproperty>
<aproperty>
<postcode></postcode>
<price></price>
<imagefilename></imagefilename>
<visits></visits>
</aproperty>
<aproperty>
<postcode></postcode>
<price></price>
<imagefilename></imagefilename>
<visits></visits>
</aproperty>
<aproperty>
<postcode></postcode>
<price></price>
<imagefilename></imagefilename>
<visits></visits>
</aproperty>
</allproperty>
I will suggest you to use XMLWriter instead, because it is best suited for that (and it's also built-in like SimpleXML):
$fp = fopen('data.txt', 'r');
$xml = new XMLWriter;
$xml->openURI('php://output');
$xml->setIndent(true); // makes output cleaner
$xml->startElement('allproperty');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$xml->startElement('aproperty');
$xml->writeElement('postcode', $line[0]);
$xml->writeElement('price', $line[1]);
$xml->writeElement('imagefilename', $line[2]);
$xml->writeElement('visits', $line[3]);
$xml->endElement();
}
$xml->endElement();
Of course, you can change the php://output argument to a filename if you want it to output to a file.
Although I think XMLWriter is best suited for that task (like in my other answer), if you really want to do it with SimpleXML, here's how:
$fp = fopen('data.txt', 'r');
$xml = new SimpleXMLElement('<allproperty></allproperty>');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$node = $xml->addChild('aproperty');
$node->addChild('postcode', $line[0]);
$node->addChild('price', $line[1]);
$node->addChild('imagefilename', $line[2]);
$node->addChild('visits', $line[3]);
}
echo $xml->saveXML();
You will notice that the output is not as clean: it's because SimpleXML doesn't allow you to automatically indent tags.
Let say a text file contain
Hello everyone, My name is Alice, i stay in Canada.
How do i use php to find "Alice" and replace it with "John".
$filename = "C:\intro.txt";
$fp = fopen($filename, 'w');
//fwrite($fp, $string);
fclose($fp);
$contents = file_get_contents($filename);
$new_contents = str_replace('Alice', 'John', $contents);
file_put_contents($filename, $new_contents);
Read the file into memory using fread(). Use str_replace() and write it back.
If its a big file, use iteration instead of reading all into memory
$f = fopen("file","r");
if($f){
while( !feof($f) ){
$line = fgets($f,4096);
if ( (stripos($line,"Alice")!==FALSE) ){
$line=preg_replace("/Alice/","John",$line);
}
print $line;
}
fclose($f);
}