output or write to a xml file? - php

$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();
im using this script to convert text file into a xml file, but i want to output it to a file, how can i do this simpleXML, cheers

file_put_contents function would do it. The function take a filename and some content and save it to the file.
So retaking your example you would just to replace the echo statement by file_put_contents.
$xml = new SimpleXMLElement('<allproperty></allproperty>');
$fp = fopen('data.txt', 'r');
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]);
}
file_put_contents('data_out.xml',$xml->saveXML());

For the record, you can use asXML() for that. I mean, it's right there in the manual, just read it and your life will get easier. (I assume, perhaps asking StackOverflow for basic stuff is easier for some)
Also, and this one is more circumstantial, you don't necessarily need to use addChild() for every child. If there is no child of that name, it can be assigned directly using the object property notation:
$fp = fopen('data.txt', 'r');
$xml = new SimpleXMLElement('<allproperty />');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$node = $xml->addChild('aproperty');
$node->postcode = $line[0];
$node->price = $line[1];
$node->imagefilename = $line[2];
$node->visits = $line[3];
}
$xml->asXML('data.xml');

Related

create multiple directories using loop in php

I am taking data from text file( data is: daa1 daa2 daa3 on separate lines) then trying to make folders with exact name but only daa3 folders is created. Also when i use integer it creates all folders, same is the case with static string i.e "faraz".
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$line =0;
while ( $line < 5 )
{
$a = fgets($f, 100);
$nl = mb_strtolower($line);
$nl = "checkmeck/".$nl;
$nl = $nl."faraz"; // it works for static value i.e for faraz
//$nl = $nl.$a; // i want this to be the name of folder
if (!file_exists($nl)) {
mkdir($nl, 0777, true);
}
$line++;
}
kindly help
use feof function its much better to get file content also line by line
Check this full code
$file = __DIR__."/dataFile.txt";
$linecount = 0;
$handle = fopen($file, "r");
$mainFolder = "checkmeck";
while(!feof($handle))
{
$line = fgets($handle);
$foldername = $mainFolder."/".trim($line);
//$line is line name daa1,daa2,daa3 etc
if (!file_exists($foldername)) {
mkdir($foldername, 0777, true);
}
$linecount++;
unset($line);
}
fclose($handle);
output folders
1countfaraz
2countfaraz
3countfaraz
Not sure why you're having trouble with your code, but I find it to be more straightforward to use file_get_contents() instead of fopen() and fgets():
$file = __DIR__."/dataFile.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$nl = "checkmeck/". $line;
if (!file_exists($nl)) {
echo 'Creating file '. $nl . PHP_EOL;
mkdir($nl, 0777, true);
echo 'File '. $nl .' has been created'. PHP_EOL;
} else {
echo 'File '. $nl .' already exists'. PHP_EOL;
}
}
The echo statements above are for debugging so that you can see what your code is doing. Once it is working correctly, you can remove them.
So you get the entire file contents, split it (explode()) by the newline character (\n), and then loop through the lines in the file. If what you said is true, and the file looks like:
daa1
daa2
daa3
...then it should create the following folders:
checkmeck/daa1
checkmeck/daa2
checkmeck/daa3

How can I get the total number of rows in a CSV file with PHP?

Using PHP, how can I get the total number of rows that are in a CSV file? I'm using this method but cannot get it to work properly.
if (($fp = fopen("test.csv", "r")) !== FALSE) {
while (($record = fgetcsv($fp)) !== FALSE) {
$row++;
}
echo $row;
}
Create a new file reference using SplFileObject:
$file = new SplFileObject('test.csv', 'r');
Try to seek to the highest Int PHP can handle:
$file->seek(PHP_INT_MAX);
Then actually it will seek to the highest line it could in the file, there is your last line and the last line + 1 is equals to your total lines:
echo $file->key() + 1;
Tricky, but this will avoid you from loading the file contents into memory, which is a very cool thing to do when dealing with really large files.
Here's another option using file() to read the entire file into an array, automatically parsing new lines etc:
$fp = file('test.csv');
echo count($fp);
Also, since PHP5, you can pass in the FILE_SKIP_EMPTY_LINES... to skip empty lines, if you want to:
$fp = file('test.csv', FILE_SKIP_EMPTY_LINES);
Manual: http://php.net/manual/en/function.file.php
Try
$c =0;
$fp = fopen("test.csv","r");
if($fp){
while(!feof($fp)){
$content = fgets($fp);
if($content) $c++;
}
}
fclose($fp);
echo $c;
I know that this is pretty old, but actually I ran into the same question.
As a solution I would assume to use linux specific logic:
$rows = shell_exec('$(/bin/which cat) file.csv | $(/bin/which tr) "\r" "\n" | $(which wc) -l');
NOTE: this only works for linux only and this only should be used if you are 100% certain that your file has no multiline-cells
CSV rows are separated by line breaks. Therefore, split the rows by line breaks, and you will get an array of rows, which is countable.
if (($fp = fopen("test.csv", "r")) !== FALSE) {
$rows = explode("\n", $fp);
$length = count($rows);
echo $length;
}
Note; none of higher-upvoted solutions that count lines in the file are reliable, as they are only counting the lines, not the csv entries (which can contain newline characters)
I'm using a similar solution to op, and it works perfectly, but with op's code the while part can break on empty lines, which is potentially his problem.
So it looks like this (edited op's code)
$rowCount=0;
if (($fp = fopen("test.csv", "r")) !== FALSE) {
while(!feof($fp)) {
$data = fgetcsv($fp , 0 , ',' , '"', '"' );
if(empty($data)) continue; //empty row
$rowCount++;
}
fclose($fp);
}
echo $rowCount;
I find this the most reliable:
$file = new SplFileObject('file.csv', 'r');
$file->setFlags(
SplFileObject::READ_CSV |
SplFileObject::READ_AHEAD |
SplFileObject::SKIP_EMPTY |
SplFileObject::DROP_NEW_LINE
);
$file->seek(PHP_INT_MAX);
$lineCount = $file->key() + 1;
I know this is an old post, but I've been googling this issue, and found that the only problem with the original code was that you need to define $row outside the while loop, like this:
if (($fp = fopen("test.csv", "r")) !== FALSE) {
$row = 1;
while (($record = fgetcsv($fp)) !== FALSE) {
$row++;
}
Just in case it helps someone :)
echo $row;
}
In case you are getting the file from a form
$file = $_FILES['csv']['tmp_name'];
$fp = new SplFileObject($file, 'r');
$fp->seek(PHP_INT_MAX);
echo $fp->key() + 1;
$fp->rewind();
Works like charm!!!!!!!!!!!!!!!!!!
$filename=$_FILES['sel_file']['tmp_name'];
$file=fopen($filename,"r");
$RowCount=0;
while ((fgetcsv($file)) !== FALSE)
{
$RowCount++;
}
echo $RowCount;
fclose($file);

Parse CSV file of links to php array, feed these links to simplehtmldom

I have a php code that will read and parse csv files into a multiline array, what i need to do next is to take this array and let simplehtmldom fire off a crawler to return some company stocks info.
The php code for the CSV parser is
$arrCSV = array();
// Opening up the CSV file
if (($handle = fopen("NASDAQ.csv", "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row $data is the variable for each line of the array
$c = count($data);
//Populate the array
for ($x=0;$x<$c;$x++) {
$arrCSV[$key][$x] = $data[$x];
}
$key++;
} // end while
// Close the CSV file
fclose($handle);
} // end if
echo "<pre>";
echo print_r($arrCSV);
echo "</pre>";
This works great and parses the array line by line, $data being the variable for each line. What i need to do now is to get this to be read via simplehtmldom, which is where it breaks down, im looking at using this code or something very similar, im pretty inexperienced at this but guess i would be needing a foreach statement somewhere along the line.
This is the simplehtmldom code
$html = file_get_html($data);
$html->find('div[class="detailsDataContainerLt"]');
$tickerdetails = ("$es[0]");
$FileHandle2 = fopen($data, 'w') or die("can't open file");
fwrite($FileHandle2, $tickerdetails);
fclose($FileHandle2);
fclose($handle);
So my qyestion is how can i get them both working together, i jave checked out simplehtmldom manual page several times and find it a littlebit vague in this area, the simplehtmldom code above is what i use in another function but by direclty linking so i know that it works.
regards
Martin
Your loop could be reduced to (yes, it's the same):
while ($data = fgetcsv($handle, 0, ',')) {
$arrCSV[] = $data;
}
Using SimpleXML instead of SimpleDom (Since it's standard PHP):
foreach ($arrCSV as $row) {
$xml = simplexml_load_file($row[0]); // Change 0 to the index of the url
$result = $xml->xpath('//div[contains(concat(" ", #class, " "), " detailsDataContainerLt")]');
if ($result->length > 0) {
$file = fopen($row[1], '2'); // Change 1 to the filename you want to write to
if ($file) {
fwrite($file, (string) $result->item(0));
fclose($file);
}
}
}
that should do it if I understood correctly...

converting text file into xml using php?

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.

Need PHP script to decompress and loop through zipped file

I am using a fairly straight-forward script to open and parse several xml files that are gzipped. I also need to do the same basic operation with a ZIP file. It seems like it should be simple, but I haven't been able to find what looked like equivalent code anywhere.
Here is the simple version of what I am already doing:
$import_file = "source.gz";
$sfp = gzopen($import_file, "rb"); ///// OPEN GZIPPED data
while ($string = gzread($sfp, 4096)) { //Loop through the data
/// Parse Output And Do Stuff with $string
}
gzclose($sfp);
What would do the same thing for a zipped file?
If you have PHP 5 >= 5.2.0, PECL zip >= 1.5.0 then you may use the ZipArchive libraries:
$zip = new ZipArchive;
if ($zip->open('source.zip') === TRUE)
{
for($i = 0; $i < $zip->numFiles; $i++)
{
$fp = $zip->getStream($zip->getNameIndex($i));
if(!$fp) exit("failed\n");
while (!feof($fp)) {
$contents = fread($fp, 8192);
// do some stuff
}
fclose($fp);
}
}
else
{
echo 'Error reading zip-archive!';
}
There is a smart way to do it with ZipArchive. You can use a for loop with ZipArchive::statIndex() to get all the information you need. You can access the files by their index (ZipArchive::getFromIndex()) or name (ZipArchive::getFromName()).
For example:
function processZip(string $zipFile): bool
{
$zip = new ZipArchive();
if ($zip->open($zipFile) !== true) {
echo '<p>Can\'t open zip archive!</p>';
return false;
}
// As long as statIndex() does not return false keep iterating
for ($idx = 0; $zipFile = $zip->statIndex($idx); $idx++) {
$directory = \dirname($zipFile['name']);
if (!\is_dir($zipFile['name'])) {
// file contents
$contents = $zip->getFromIndex($idx);
}
}
$zip->close();
}

Categories