Creating HTML files from PHP files [duplicate] - php

This question already has answers here:
Save current page as HTML to server
(6 answers)
Closed 9 years ago.
I know this is outside of the ordinary use for PHP. I use PHP to generate templates for web front-ends. I then deliver these templates to a development team. They request that we deliver flat HTML files.
Is there a way to utilize PHP to save out the html version of the file. I have screen-02.php to screen-62.php. I have to individually open these in a browser and save the html as screen-02.html, screen-03.html , etc. I also have jQuery at my disposal if that helps.
Thanks in advance for any help.

using php output buffering? http://php.net/manual/en/function.ob-start.php
something like perhaps:
<?php
ob_start();
include_once("screen-01.php");
$content = ob_get_clean();
file_put_contents($fileName, $content);
?>
you could put in a loop to save all files at the same time as well, but depending on how many you should check the max execution time

I think it would be the easiest thing to write a Shell/Batch script and execute the PHP scripts from the CLI in stead of using them as a web page.
If you execute the following command:
php /some/page.php
You can generate the output that is wanted to your stdout, so if you use pipelining, you can easily do things like:
php /some/page.php >> /some/page.html
Or you can write a bash script (if you're on Linux) like this:
#!/bin/bash
for i in {1..5}
do
php /some/screen-$i.php >> /some/screen-$i.html
done
I think that will be the easiest (and fastest) approach, no other technologies are required.
If you don't have access to the PHP CLI, you can do a similar thing, but in stead of using the PHP CLI you can use wget to download the pages.

The easiest way (in my opinion) would be to use output buffering to store and then save the PHP output. You can use this without access to command-line server tools.
Create a new PHP file like so:
<?php
// Start output buffering
ob_start();
// Loop through each of the individual files
for ( $j = 0; $j<= 62; $j++ ){
ob_clean(); // Flush the output buffer
$k = str_pad( $j, 2, '0' ); // Add zeros if a single-digit number
require_once('screen-' . $k . '.php'); // Pull in your PHP file
if ( ob_get_length() > 0 ){ // If it put output into the buffer, process
$content = ob_get_contents(); // Pull buffer into $content
file_put_contents( 'screen-' $k . '.html', $content ); // Place $content into the HTML file
}
}
?>
And run it from the same server in the same path. Make sure the folder has write permissions (CHMOD) so it can create the new files. You should find it generates all your HTML files with the proper PHP output.

Maybe something like this:
<?php
$file = $_GET['file'];
$html = file_get_contents('http://yoururl.com/'.$file);
file_put_contents('./savedPages/'.$file.'.htm', $html);
?>
Call it with http://yoururl.com/savePage.php?file=yourtarget.php

When you use a templating engine like Smarty you can create the output and save it to a file without the need to display it in a browser.
$smarty = new Smarty;
$smarty->assign("variable", $variable);
$output = $smarty->fetch("templatefile.tpl");
file_put_contents("/path/to/filename.html", $output);
Smarty Documentation: http://www.smarty.net/docs/en/api.fetch.tpl
Another option would be to use the PHP outputbuffer

Related

Save the console text into a txt file? (PHP)

actual I finished writing my program. Because it is only a plugin and it runs on a external server I still want to see if I get some errors or something else in the console.
I wrote every console input with echo ...;. My question now is if it is possible to get the text of the console?
Because then I could easily safe it in a .txt file and could get access to it from the web :) - Or is there another way to get the console text?
I could probably just say fwrite(...) instand of echo ...;. But this will cost a lot of time...
Greetings and Thank You!
An alternative that could be usefull on windows would be to save all the output buffer to a txt, first check your php configuration for the console app implicit_flush must be off then
<?php
ob_start(); //before any echo
/** YOUR CODE HERE **/
$output = ob_get_contents(); //this variable has all the echoes
file_put_contents('c:\whatever.txt',$output);
ob_flush(); //shows the echoes on console
?>
If your goal is to create a text file to access, then you should create a text file directly.
(do this instead of echoing to console)
$output = $consoleData . "\n";
$output .= $moreConsoleData . "\n";
(Once you've completed that, just create the file:)
$file = fopen('output.txt', 'a');
fwrite($file, $output);
fclose($file);
Of course, this is sparse - you should also check that the file exists, create it if necessary, etc.
For console (commando line interface) you can redirect the output of your script:
php yourscript.php > path-of-your-file.txt
If you haven't access to a command line interface or to edit the cronjob line, you can duplicate the starndar output at the begining of the script:
$fdout = fopen('path-to-your-script.txt', 'wb');
eio_dup2($fdout, STDOUT);
eio_event_loop();
fclose($fdout);
(eio is an pecl extension)
If you are running the script using the console (i.e. php yourscript.php), you can easily save the output my modifying your command to:
php yourscript.php > path/to/log.txt
The above command will capture all output by the script and save it to log.txt. Change the paths for your script / log as required.

How to process PHP code in a text string, to prevent it from being seen as text?

I'm using the Redactor editor in a custom built CMS. Redactor has an option, phpTags, which when set to true allows PHP code to be entered and saved as part of the content.
The issue is that this PHP code is being seen as text, not PHP code, and is being escaped rather than being processed.
For example, if I enter this in the editor:
<?php echo date('Y'); ?>
Instead of the year being displayed, the code is commented out in the page's markup, like so:
<!--?php echo date('Y'); ?-->
How can I prevent this from happening? To make sure the PHP code is processed/interpreted as such by the server?
I should probably mention that there are a lot of people using this CMS, so there's no way to know what PHP code may be added in advance.
Perhaps
<!-- <?php echo date('Y') ?> -->
You can't change PHP's opening/closing tags like you are, not without a recompile of PHP. If you want to hide php's output, then surround the entire php code block with html comment tags.
PHP won't care about the html comments. It couldn't care at all what it's embedded in. You could stuff a PHP code block into the middle of a .jpg file and it'd still execute, as long as the webserver's configured to run .jpg files through the PHP interpreter.
To fix this issue I took the content I was previously just displaying via echo, and saved it to a temporary file.
Then I turned on output buffering, included that temporary file in the PHP script, and grabbed its contents via ob_get_contents().
This allowed me to display the content with all the PHP within having been parsed. Here's the code for reference:
// Create path to temporary file
$tmpPath = '/temp.php';
// Set file variable to null for error checking
$tmpFile = NULL;
// Try creating the temporary file
if ( $tmpFile = fopen($tmpPath, 'w') ) {
if ( fwrite($tmpFile, $postContent) === FALSE ) {
// Do something if the file can't be written to
} else {
// Close file
fclose($tmpFile);
}
}
// Start output buffereing
ob_start();
// Include the temporary file created above
include $tmpPath;
// Save buffered contents to a variable
$content = ob_get_contents();
// End output buffering
ob_end_clean();
// Display content
echo $content;
I appreciate the various comments to my question, as it helped prod me in the right direction to getting this figured out.

Replace HTML elements content of a PHP/HTML file with PHP

Problem
I'm trying to edit HTML/PHP files server side with PHP. With AJAX Post I send three different values to the server:
the url of the page that needs to be edited
the id of the element that needs to be edited
the new content for the element
The PHP file I have now looks like this:
<?php
$data = json_decode(stripslashes($_POST['data']));
$count = 0;
foreach ($data as $i => $array) {
if (!is_array($array) && $count == 0){
$count = 1;
// $array = file url
}
elseif (is_array($array)) {
foreach($array as $i => $content){
// $array[0] = id's
// $array[1] = contents
}
}
}
?>
As you can see I wrapped the variables in an array so it's possible to edit multiple elements at a time.
I've been looking for a solution for hours but can't make up my mind and tell what's the best/possible solution.
Solution
I tried creating a new DOMElement and load in the html, but when dealing with a PHP file, this solution isn't possible since it can't save php files:
$html = new DOMDocument();
$html->loadHTMLFile('file.php');
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");
(From this answer)
Opening a file, writing in it and saving it comes is another way to do this. But I guess I must be using str_replace or preg_replace this way.
$fname = "demo.txt";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("oldword", "newword", $content);
$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
(From this page)
I read everywhere that str_replace and preg_replace are risky 'caus I'm trying to edit all kinds of DOM elements, and not a specific string/element. I guess the code below comes close to what I'm trying to achieve but I can't really trust it..
$replace_with = 'id="myID">' . $replacement_content . '</';
if ($updated = preg_replace('#id="myID">.*?</#Umsi', $replace_with, $file)) {
// write the contents of $file back to index.php, and then refresh the page.
file_put_contents('file.php', $updated);
}
(From this answer)
Question
In short: what is the best solution, or is it even possible to edit HTML elements content in different file types with only an id provided?
Wished steps:
get file from url
find element with id
replace it's content
First of all, you are right in not wanting to use a regex function for HTML parsing. See the answer here.
I'm going to answer this question under the presumption you are committed to the idea of retrieving PHP files server-side before they are interpreted. There is an issue with your approach right now, since you seem to be under the impression that you can retrieve the source PHP file by the URL parameter - but that's the location of the result (interpreted PHP). So be careful your structure does what you want.
I am under the assumption that the PHP files are structured like this:
<?php include_some_header(); ?>
<tag>...</tag>
<!-- some HTML -->
<?php //some code ?>
<tag>...</tag>
<!-- some more HTML -->
<?php //some code ?>
Your problem now is that you cannot use an HTML reader (and writer), since your file is not HTML. My answer is that you should restructure your code, separating templating language from business logic. Get started with some templating language. Afterwards, you'll be able to open the template, without the code, and write back the template using a DOM parser and writer.
Your only alternative in your current setup is to use the replace function as you have found in this answer. It's ugly. It might break. But it's definitely not impossible. Make backups before writing over your own code with your own code.

pass mysql value from php page to a joomla article and display relevant data inside of a joomla article

we are developing an application.website is being developed by joomla.Admin panel is being developed using a pure php.on index page(joomla), we are displaying some details from the backend.
my question is this, when we click on one of the records on that page can we display the relevant data inside of a article?
Hope i asked the question clearly.
please share your thoughts with us.
thanks in advance
Yes, you can do this, if I understand your question correctly.
Open up Joomla's main index.php. This is the index.php in the html root, not the index.php in one of the template folders.
Near the bottom of the file, or maybe the very last line you will see something like this:
// Return the response.
echo $app
Replace this line with the following:
// Return the response.
// parse $app for server side includes statements and execute them
// note: this will only work for executable code, it will not import text or html files
// we would need to check to see if the file were executable, then read it rather than execute it if it were not
$output = $app;
while(ereg('(<!--#include virtual="([^&]+)" -->)',$output,$groups)){ // extract the ssi command and the command
$i = 0;
while(!$inline){ // sometimes exec() fails for want of memory so we try a few times
exec($groups[2],$array); // get the output from the command
foreach ($array as $element) // concatenate the lines of output into a single string
$inline = $inline . $element . "\n"; // appending a new line makes the html source more readable
$i++;
if($inline | $i > 5)
break;
sleep(1);
}
$output = ereg_replace($groups[1],$inline,$output); // replace the ssi command with the output
}
echo $output;
This will allow you to place a standard server side includes statement in your article. Fore example if you want to execute a php file in the same directory as your index.php and the file is called dynamic_content.php you would type this in your article:
<!--#include virtual="dynamic_content.php"-->
The output of that script will then be included in the text of the article. You can have multiple ssi commands in the same article.

Importing a php.inc file into a PERL program

I'm trying to use 1 include file for both perl and php
Is there a nice way to import a myphp.inc file within perl?
$ cat myphp.inc
<?php
$some_var="hello world";
?>
Using the above in my test.php works fine:
include "myphp.inc";
If I remove the < ? php then test.php will just print out the contents of the myphp.inc file... if I leave them in then my perl programs complains with:
Unterminated <> operator
I've seen the perl module: PHP::Include but I would like to stay away from external modules if possible.
Anyone have ideas on doing this??
Don't try to write code that is both PHP and Perl, they are different languages, even if they have some shared ancestry. If you want to share data between the two, then use a structured data format. JSON is a popular flavour. PHP has parse_json and Perl has the JSON module.
I would like to stay away from external modules if possible
Code reuse is a virtue … although there is nothing stopping you reimplementing the modules from scratch.
Ideally you would store the shared/configuration data in a format easily readable in both PHP and Perl. XML, JSON, or a simple text file with key-value pairs (as in the .ini file that simbabque suggests) would work great.
If you are determined to read the PHP file in Perl but you do not want to use a module such as PHP::Include then you are left with writing something like this:
use IO::File;
sub require_php {
my $source_filename = $_[0];
my $dest_filename = 'temp.inc.pl';
open my $source, $source_filename or die "Could not open $source_filename: $!";
open my $destination, '>>'.$dest_filename or die "Cound not open file for writing";
while(my $line = <$source>) {
if(index($line,'<?php')==-1 && index($line,'?>')==-1) {
print $destination $line
}
}
close $destination;
close $source;
require $dest_filename;
unlink $dest_filename;
}
our $some_var = '';
require_php('myphp.inc');
which will end with $some_var having the value of "hello world".

Categories