Russian language

How do I add PHP code/file to HTML(.html) files?

Neither of these work. My server offers PHP, and when I use a the .php extension, it works properly. Is this a problem or do I have to change the preferences in php.ini ?

You would have to change your server (I assume apache) to serve html files as php, but why do you want the extension to be html instead of php?

@Death I didn’t mean to imply that it can only be done with apache, I just assumed he was using apache.

12 Answers 12

You can’t run PHP in .html files because the server does not recognize that as a valid PHP extension unless you tell it to. To do this you need to create a .htaccess file in your root web directory and add this line to it:

AddType application/x-httpd-php .htm .html 

This will tell Apache to process files with a .htm or .html file extension as PHP files.

While this is right I think a more important question is why do this? Moreover, he should update server config rather than use .htaccess if that’s an option.

I’ve done this on numerous occasions to hide the fact that I’m using PHP (in addition to other things)

@NathanLong w3.org/TR/cooluris Specifically, «Keep implementation-specific bits and pieces such as .php and .asp out of your URIs, you may want to change technologies later.» in section 4.5.

@EricFinn — that’s a good guideline. But having the server process .html files as PHP isn’t necessary even, or helpful, in following it. You want users to visit example.com/foo . You could use that URL to serve PHP content regardless of the file names on your server. If users already have foo.html bookmarked, you could still serve foo.php without renaming the file.

I think writing PHP into an .html file is confusing and anti-natural. Why would you do that??

Anyway, if what you want is to execute PHP files and show them as .html in the address bar, an easiest solution would be using .php as normal, and write a rule in your .htaccess like this:

What if i use PHP + HTML? which format should i use? I’m quite confused. My page has really short code based on PHP and there are many codes in HTML. So what i was going to do is to make a HTML file. Is this a bad habit?

Читайте также:  Hibernate java util list

In order to use php in .html files, you must associate them with your PHP processor in your HTTP server’s config file. In Apache, that looks like this:

AddHandler application/x-httpd-php .html 

@PatrickT Simplest way to compare is that AddHandler is an «input» mapping — it maps an incoming file extension to a handler. AddType modifies the output MIME type header. See the note here: httpd.apache.org/docs/2.4/mod/mod_mime.html#addtype

You can modify .htaccess like others said, but the fastest solution is to rename the file extension to .php

AddHandler application/x-httpd-php .html 

to httpd.conf file for what you want to do. But remember, if you do this then your web server will be very slow, because it will be parsing even static code which will not contain php code. So the better way will be to make the file extension .phtml instead of just .html .

For having .html files parsed as well, you need to set the appropriate handler in your server config.

For Apache httpd 2.X this is the following line

AddHandler application/x-httpd-php .html 

See the PHP docu for information on your specific server installation.

By default you can’t use PHP in HTML pages.

To do that, modify your .htacccess file with the following:

AddType application/x-httpd-php .html 

Create an empty file using notepad and name it .htaccess ,Then copy that file in your project directory and add this line and save.

AddType application/x-httpd-php .htm .html 

else save the .html file using .php as php can support html,and save it in computer/var/www/html path(linux)

If you only have php code in one html file but have multiple other files that only contain html code, you can add the following to your .htaccess file so it will only serve that particular file as php.

 AddType application/x-httpd-php .html //you may need to use x-httpd-php5 if you are using php 5 or higher 

This will make the PHP executable ONLY on the «yourpage.html» file and not on all of your html pages which will prevent slowdown on your entire server.

As to why someone might want to serve php via an html file, I use the IMPORTHTML function in google spreadsheets to import JSON data from an external url that must be parsed with php to clean it up and build an html table. So far I haven’t found any way to import a .php file into google spreadsheets so it must be saved as an .html file for the function to work. Being able to serve php via an .html file is necessary for that particular use.

Читайте также:  Простейшая программа калькулятор на java

Источник

DOMDocument::saveHTML

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

Optional parameter to output a subset of the document.

Return Values

Returns the HTML, or false if an error occurred.

Examples

Example #1 Saving a HTML tree into a string

$root = $doc -> createElement ( ‘html’ );
$root = $doc -> appendChild ( $root );

$head = $doc -> createElement ( ‘head’ );
$head = $root -> appendChild ( $head );

$title = $doc -> createElement ( ‘title’ );
$title = $head -> appendChild ( $title );

$text = $doc -> createTextNode ( ‘This is the title’ );
$text = $title -> appendChild ( $text );

See Also

  • DOMDocument::saveHTMLFile() — Dumps the internal document into a file using HTML formatting
  • DOMDocument::loadHTML() — Load HTML from a string
  • DOMDocument::loadHTMLFile() — Load HTML from a file

User Contributed Notes 18 notes

As of PHP 5.4 and Libxml 2.6, there is currently simpler approach:

when you load html as this

$html->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

in the output, there will be no doctype, html or body tags

When saving HTML fragment initiated with LIBXML_HTML_NOIMPLIED option, it will end up being «broken» as libxml requires root element. libxml will attempt to fix the fragment by adding closing tag at the end of string based on the first opened tag it encounters in the fragment.

Foo

bar

Foo

bar

Easiest workaround is adding root tag yourself and stripping it later:

$html->loadHTML(‘‘ . $content .’‘, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$content = str_replace(array(‘‘,’‘) , » , $html->saveHTML());

This method, as of 5.2.6, will automatically add and tags to the document if they are missing, without asking whether you want them. In my application, I needed to use the DOM methods to manipulate just a fragment of html, so these tags were rather unhelpful.

Here’s a simple hack to remove them in case, like me, all you wanted to do was perform a few operations on an HTML fragment.

I am using this solution to prevent tags and the doctype from being added to the HTML string automatically:

Читайте также:  Html header top padding

$html = ‘

Hello world!

‘ ;
$html = ‘

‘ . $html . ‘

‘ ;
$doc = new DOMDocument ;
$doc -> loadHTML ( $html );
echo substr ( $doc -> saveXML ( $doc -> getElementsByTagName ( ‘div’ )-> item ( 0 )), 5 , — 6 )

// Outputs: «

Hello world!

»
?>

Since PHP/5.3.6, DOMDocument->saveHTML() accepts an optional DOMNode parameter similarly to DOMDocument->saveXML():

If you load HTML from a string ensure the charset is set.

Otherwise the charset will be ISO-8859-1!

Tested in PHP 5.2.9-2 and PHP 5.2.17.
saveHTML() игнорирует свойство DOMDocument->encoding. Метод saveHTML() сохраняет html-документ в кодировке, которая указана в теге исходного (загруженного) html-документа.
saveHTML() ignores property DOMDocument->encoding. Method saveHTML() saves the html-document encoding, which is specified in the tag source (downloaded) html-document.
Example:
file.html. Кодировка файла должна совпадать с указанной в теге . The encoding of the file must match the specified tag .


Русский язык

error_reporting (- 1 );
$document =new domDocument ( ‘1.0’ , ‘UTF-8’ );
$document -> preserveWhiteSpace = false ;
$document -> loadHTMLFile ( ‘file.html’ );
$document -> formatOutput = true ;
$document -> encoding = ‘UTF-8’ ;
$htm = $document -> saveHTML ();
echo «Записано байт. Recorded bytes: » . file_put_contents ( ‘file_new.html’ , $htm );
?>
file_new.html будет в кодировке Windows-1251 (НЕ в UTF-8).
file_new.html will be encoded in Windows-1251 (not in UTF-8).

saveHTML() и file_put_contents() позволяют преодолеть недостаток метода saveHTMLFile().
Смотрите мой комментарий к методу saveHTMLFile().
saveHTML() and file_put_contents() allows you to overcome the lack of a method saveHTMLFile().
See my comment on the method saveHTMLFile().
http://php.net/manual/ru/domdocument.savehtmlfile.php

To solve the script tag problem just add an empty text node to the script node and DOMDocument will render nicely.

To avoid script tags from being output as

$doc = new DOMDocument ();
$doc -> loadXML ( $xmlstring );
$fragment = $doc -> createDocumentFragment ();
/* Append the script element to the fragment using raw XML strings (will be preserved in their raw form) and if succesful proceed to insert it in the DOM tree */
if( $fragment -> appendXML ( «» ) <
$xpath = new DOMXpath ( $doc );
$resultlist = $xpath -> query ( «//*[local-name() = ‘html’]/*[local-name() = ‘head’]» ); /* namespace-safe method to find all head elements which are childs of the html element, should only return 1 match */
foreach( $resultlist as $headnode ) // insert the script tag
$headnode -> appendChild ( $fragment );
>
$doc -> saveXML (); /* and our script tags will still be */

If you want a simpler way to get around the

$script = $doc -> createElement ( ‘script’ );\
// Creating an empty text node forces
$script -> appendChild ( $doc -> createTextNode ( » ));
$head -> appendChild ( $script );

If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you’re reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.

header ( ‘Content-Type: text/html; charset=iso-8859-1’ );
?>

Источник

Create .html file with php

i want to create a new .html file using php script as i new to php i don’t understand to do it. i founded a code but it m not working.

i want that when i load my page, an new .html file should be created to my path/ directory with some entries like heading e.t.c in my html file can anyone help me??

You clearly don’t understand at all what you’re doing, try reading some tutorials to at least grasp the necessary basics. Your question and your code are not related in any way.

3 Answers 3

Best way to do it would be to write a small blank html file and save it somewhere; e.g. «template.html»

1) in PHP you can read it with

$newcontent = file_get_contents("template.html"); 

2) the open a new file with fopen, write new content, close the file. Done.

if (!file_exists('newname.html')) < $handle = fopen('path/to/new/file/newname.html','w+'); fwrite($handle,$newcontent); fclose($handle); >

So, there are two parts of creation of new file:

First you need to create content of that file. Here you can combine HTML and PHP code. For example

Or use nay template engine or code generator — and generated code save into any variable that you will use as content of created file.

And then you may create own file:

`$Filename` means name of generated file (including its path) `$Mode` means mode of file generation 

Both arguments may be passed also directly (for example fopen(‘file.ext’, ‘a’) )

Writing content of file follows

$Status = fwrite($File, $TagCode); 

And that is all — unless you would control if file was created correctly (then you use that function fwrite returns TRUE or FALSE — that you store in any variable — it is better than direct checking).

There are following modes of opening of files

  • a — file content is not overwritten; only for adding of content; new content is placed below older content
  • a+ — file content is not overwritten; for adding/reading of content; new content is placed below older content
  • r — file content may be only read
  • r+ — file content is not overwritten;, for adding/reading of content; new content is placed above older content
  • w — file content is overwritten, only for adding of content
  • w+ — file content is overwritten; for adding/reading of content

Instead functions fopen , fwrite and fclose may be used also file_puts_content , but I like fopen, fwrite and fclose more.

Источник

Оцените статью