GZ Compressing an XML sitemap file with PHP - php

I have a PHP script that generates a dynamic PHP sitemap from my site's database to an xml file using fopen() and fwrite().
How can I compress this file using GZ compression dynamically as I write it?
I tried fwrite()-ing strings that I ran through gzcompress() into the file and renaming it ".xml.gz", but it doesn't seem the file it;s creating is a well-fromed archive.

Not using fopen and fwrite but gzopen() and gzwrite() should do the trick for you.
From the manual:
# Sample #1 gzwrite() example
<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>
If i understood correctly

this is a quote from the php site that we all should keep in mind.
Take Heed 07-Nov-2010 08:50 Read the description of gzwrite() very
carefully. If the 'length' option is not specified, then the input
data will have slashes stripped on systems where magic quotes are
enabled. This is important information to know when compressing
files.
http://php.net/manual/en/function.gzwrite.php

Related

How to read any of the file type using php7?

I have tried to extract the user email addresses from my server. But the problem is maximum files are .txt but some are CSV files with txt extension. When I am trying to read and extract, I could not able to read the CSV files which with TXT extension. Here is my code:
<?php
$handle = fopen('2.txt', "r");
while(!feof($handle)) {
$string = fgets($handle);
$pattern = '/[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/i';
preg_match_all($pattern, $string, $matches);
foreach($matches[0] as $match)
{
echo $match;
echo '<br><br>';
}
}
?>
I have tried to use this code for that. The program is reading the complete file which are CSV, and line by line which are Text file. There are thousands of file and hence it is difficult to identify.
Kindly, suggest me what I should do to resolve my problem? Is there any solution which can read any format, then it will be awesome.
Well your files are different. Because of that you will have to take a different approach for each of those. In more general terms this is usually calling adapting and is mostly provided using the Adapter design pattern.
Should you use the adapter design pattern you would have a code inspecting the extension of a file to be opened and a switch with either txt or csv. Based on the value you would retrieve aTxtParseror aCsvParser` respectively.
However, before diving deep into this territory you might want to have a look at the files first. I cannot say this for sure without seeing the structures but you can. If the contents of both the text and csv files are the same then a very simple approach is to change the extension to either txt or a csv for all files and then process them using same logic, knowing files with the same extension will now be processed in the same manner.
But from what I understood the file structures actually differ. So to keep your code concise the adapter pattern, having two separate classes/functions for parsing and another one on top of that for choosing the right parsing function (this top function would actually be a form of a strategy) and running it.
Either way, I very much doubt so there is a solution for the problem you are facing as a file structure is mostly your and your own.
Ok, so problem is when CSV file has too long string line. Based on this restriction I suggest you to use example from php.net Here is an example:
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
// do your operation for searching here
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}

Difference between file, file_get_contents, and fopen in PHP

I am new to PHP, and I am not quite sure: what is the difference between the file(), file_get_contents(), and fopen() functions, and when should I use one over the other?
The first two, file and file_get_contents are very similar. They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string. The array returned by file will be separated by newline, but each element will still have the terminating newline attached, so you will still need to watch out for that.
The fopen function does something entirely different—it opens a file descriptor, which functions as a stream to read or write the file. It is a much lower-level function, a simple wrapper around the C fopen function, and simply calling fopen won't do anything but open a stream.
Once you've open a handle to the file, you can use other functions like fread and fwrite to manipulate the data the handle refers to, and once you're done, you will need to close the stream by using fclose. These give you much finer control over the file you are reading, and if you need raw binary data, you may need to use them, but usually you can stick with the higher-level functions.
So, to recap:
file — Reads entire file contents into an array of lines.
file_get_contents — Reads entire file contents into a string.
fopen — Opens a file handle that can be manipulated with other library functions, but does no reading or writing itself.
file — Reads entire file into an array
file_get_contents — Reads entire file into a string
fopen — Opens file or URL

How to read a PHP file as text file to an array?

Here is my situation.Supposing I have a PHP file named as:
myfunctions.php
Is it possible to read the contents of that PHP file (myfunctions.php) in another script using available PHP functions?
I'm using the following functions without success in reading this PHP file:
file_get_contents()
file()
It simply returned blank. One of the possible successful method was to read this PHP file as text file but I do not know how to do this..If someone has some other methods, please share. Ideally I want the output to be an array so the data I would like to obtain will be easily manipulated for use.
Thanks.
If I were you, I will change the extension on the "myfunctions.php" to "myfunctions.txt" and use the theses functions
file_get_contents()
file()
But I don't know if you are allow to change the name of the document.
file() - Reads entire file into an array
fgets() - Gets line from file pointer
fread() - Binary-safe file read
readfile() - Outputs a file
file_put_contents() - Write a string to a file
stream_get_contents() - Reads remainder of a stream into a string
stream_context_create() - Creates a stream context
You need fread. To put it into an array, you might look at explode

Unconventional .ZIP handling and find/replace in PHP

I have a slightly unconventional task I am trying to accomplish with .ZIP archives in PHP. I have a zip archive used for an automation task (It's a startup package for Amazon EC2 instances) which contains a number of text and xml files. What I need to do is find/replace a few pieces of text within those files, and output a BASE 64 encoded string (not write a new .zip file) using PHP on the fly.
I have no problem with getting the file contents and base64 enconding them with file_get_contents(), and base64_encode(), or the find/replace, it's the unzipping, and zipping to and from strings I can't seem to figure out.
I would like to avoid unzipping the archive, copying the files, editing the files writing a new .zip to disk, and then getting the contents and encoding that. I was hoping there might be a solution that looks more like this:
Get the contents of the zip file into a string.
$originalZipFile = file_get_contents('Path/To/ZipFile');
"Unzip" the data in that string, to a new string to expose the bits of text I want to find/replace.
$unzippedFile = someFunction($originalZipFile);
Find and replace bits of text.
$processedString = str_replace($find, $replace, $unzippedFile);
"Rezip" the processed string into a new string.
$rezippedFile = someOtherFunction($processedString);
Base64 encode the "rezziped" string.
$desiredOutputString = base64_encode($rezippedFile);
I have looked at the PHP ZipArchive class, but it doesn't seem to have the functions I'm looking for.
Any insights are greatly appreciated!
-Oliver
Well, I believe I found a pretty good solution to this. For any others looking for similar solutions, I would recommend looking at the ZipStream-PHP class by Paul Duncan.
With this class, you are able to dynamically write files, contents, and directories to a zip file, which is then streamed without writing a file to disk.
Pretty automagical.

PHP zip_open() and php://temp, can't seem to open

Not sure if this is possible, but it's become an academic struggle now.
Using the __halt_compiler() trick to embed binary data in a PHP file, I've successfully created a self-opening script which will fseek() to __COMPILER_HALT_OFFSET__ (not too hard seeing as this precise example is documented in the manual)
Anyways, I've stored a small lump of binary ZIP data (a single folder containing a single file that says "hello world") after my call to __halt_compiler()
What I've tried to do is copy the data directly to the php://temp stream, and have done so with success (if I rewind() and passthru() the temporary stream handle, it dumps the data)
$php = fopen(__FILE__, 'rb');
$tmp = fopen('php://temp', 'r+b');
fseek($php, __COMPILER_HALT_OFFSET__);
stream_copy_to_stream($php, $tmp);
My problem comes with trying to now open php://temp1 with zip_open()
$zip = zip_open('php://temp');
1From what I can see (despite other such possibilities as lack of stream support with zip_open()) the problem here is the inherent non-permanence of data in php://memory and php://temp streams between handles. If this can be worked around, perhaps it is in fact possible.
It keeps kicking back error code 11, which I have found no2 documentation on (seemingly, like most other possible error codes)
var_dump($zip); // int(11)
2 As #cweiske pointed out, error code 11 = ZipArchive::ER_OPEN, Can't open file
Is this consequence to my attempt at using the php://temp stream, or some other possible issue? I'm also aware there exists an OOP approach (ZipArchive, et al.) but I figured I'd start with the basics.
Any ideas?
11 is the constant ZIPARCHIVE::ER_OPEN, which the manual describes with
Can't open file
Note that the manual does not state that stream wrappers may be used.
Please think about using PHP's phar extension - it does what you want, and is well tested.

Categories