Displaying HTML code - php

How can stop HTML code from rendering and display it as standard text, so my users can simply copy and paste it for their own usage?

You could use the function htmlentities(). Have a look at the manual.
Please note that by default the data will be returned using the ISO-8859-1 character set. You might want to change the third parameter to UTF-8.
For example:
$html = "<div>Some text</div>";
echo htmlentities($html);

Use PHP to set the content type:
header("Content-Type: text/plain");

You parse it into markup which uses HTML entities, for example instead of using:
<body>
you would instead use entity codes to escape the markup characters, like this:
<body>
There are plenty of references to be found which list entity codes, and it's pretty easy to parse and escape HTML in most programming languages.

HTML code can be displayed using php script by using functions htmlentities() and htmlspecialchars(). For understanding this concept consider the following example:
<?php
$a="<h1>heading tag: used for heading tags</h1>";
echo htmlentities($a)."<br/>";
echo htmlspecialchars($a);
?>
Output will be:
<h1>heading tag: used for heading tags</h1>
<h1>heading tag: used for heading tags</h1>

Related

Replace a string with HTML

I'm using str_replace as follows:
<html>
<head>
</head>
<body>
<script type="text/php">
$new_str = str_replace( '[[str_to_replace]]' , $GLOBALS['html'] , $original_str );
</script>
<div class="wrapper">[[str_to_replace]]</div>
<?php
// multiple includes
// lots and lots of code
//PHP code to calculate HTML code
//value of $html depends on data calculated after div.wrapper is drawn
$GLOBALS['html'] = '<input type="text" />';
?>
</body>
</html>
I'm forced to wrap the PHP code in a script tag because the document is getting passed to a library as an HTML document. The library has the ability to execute PHP code inside script tags but in this case is working oddly.
What I'm expecting:
[[str_to_replace]] should become an HTML input field.
What I'm getting:
[[str_to_replace]] becomes the literal string <input type="text" />.
How do I get the second result?
You're likely misinterpreting wht you can do with inline script. In dompdf HTML is parsed separately from inline script. Any HTML you insert into the document using inline script will be treated as plain text. What you should be doing is parsing your document first then passing the results to dompdf.
FYI, It's hard to see from your sample exactly what you're doing in the code. Plus we can't see what's going on with dompdf. I'm having a hard time seeing how everything ties together.
It sounds like what you're trying to do is to replace the string with decoded HTML entities. You'll probably want to do:
$htmlEntityString = '&'; // String containing HTML entities that you want to decode.
$new_str = str_replace( '[[str_to_replace]]' , html_entity_decode($htmlEntityString) , $original_str );
In this case, whatever HTML you have with HTML entity form will be decoded and will replace the substring.
Read more about it for all the options:
http://php.net/manual/en/function.html-entity-decode.php

Prevent php from rendering/executing between pre tags

I'm using pre tags to display codesnippets on my website, these snippets contain html and php.
So far I've used Jquery to convert html in the codesnippets to plain text, but the php tags are still being executed.
The code that I used for converting the html contents of the pre tag to plain text:
$(document).ready(function(){
$("pre").text($("pre").html());
});
An example of what I'm using it on:
<pre>
<p>paragraph Content</p>
<h1>html code</h1>
<?php echo "this is php example code"; ?>
</pre>
The first 2 lines display in the browser with the tags and everything perfectly, but the third line execute the php tags rendering only this php example code. Can anyone help me out so I can display the php tags in my code snippet aswell?
Also if anybody knows a better solution to rendering html/css and php as a code snippet on your website It would be really helpfull.
The problem with your approach is, that you try to influence the rendering after the browser has processed the file. When you look at the sourcecode of your page, you will notice that there really is nothing else than "this php example code" in there, because the server parsed that part of your code and executed it, which leads to nothing but the string you put into that echo command.
You need to handle your output before your send it to the client and fetch all occurrences of <pre> and </pre> to replace all < and > between them with their respective HTML entities.
Have a look at this question to find out the best approach to parse the HTML and get the appropriate elements in order to modify them.
You should escape the < and > symbols - replace them with their HTML entities, < and > respectively ;)
If you want a total and comprehensive conversion to HTML entities, try converting them over at http://centricle.com/tools/html-entities
Generally it's good practice to convert all symbols to their respective HTML entities within a code block.
Try to replace <?php ... ?> with
<? .... >
<pre>
<p>paragraph Content</p>
<h1>html code</h1>
<?php echo "this is php example code"; ?>
</pre>
Here's a JSFiddle example so you can see how it renders on the page.

replace html of tags with php regex

I have a situation in which I think I may have to use regex to alter html tag content or src based on the class attribute.
To document I will be parsing will be either nicely formed html, partial html or php files.
EG I would need to change/fill these tags with inner content: fileX.php
<?php
echo <<<_END
<div class="identifyingClass1"></div>
<div class="identifyingClass2"><span>holding content</span></div>
<img src='http://source.com/to/change' class='identifyingClass3' alt='descrip'/>
_END;
Resulting fileX.php
<?php
echo <<<_END
<div class="identifyingClass1">New content jsd soisvkbsdv</div>
<div class="identifyingClass2">More new content</div>
<img src='new/source.tiff' class='identifyingClass3' alt='descrip'/>
_END;
The html could be complete, could be separated by php, be as is, be inside a hereDOC...
Is the best way to achieve this to just use regex or has anyone seen or used a class for this kind of thing?
Regex is evil for such case. Better you work on the generated html. Here's how you do it.
Enable output buffering. On the ob_start function add your own callback. Process the generated html with DOMDocument inside the handler. Something like this,
function my_handler($contents){
$doc = DOMDocument::loadHTML ($contents);
// change your document here and return it later
return $doc->saveHTML();
}
ob_start('my_handler');
As already stated, RegEx is not recommended for doing such kind of things. Look at this excellent answer. My personal favourite is SimleDom which provides a jQuery-like syntax and makes working with HTML in PHP actually joyful ;).

Replace <pre> tags with <code>

What i need to do is to replace all pre tags with code tags.
Example
<pre lang="php">
echo "test";
</pre>
Becomes
<code>
echo "test";
</code>
<pre lang="html4strict">
<div id="test">Hello</div>
</pre>
Becomes
<code>
<div id="test">Hello</div>
</code>
And so on..
Default DOM functions of php have a lot of problems because of the greek text inside.
I think Simple HTML DOM Parser is what i need but i cant figure out how to do what i want. Any ideas?
UPDATE
Im moving to a new CMS thats why im writing a script to format all posts to the correct format before inserting into DB. I cant use pre tags in the new CMS.
Why not KISS (Keep It Simple, Stupid):
echo str_replace(
array('<pre>', '</pre>'),
array('<code>', '</code>'),
$your_html_with_pre_tags
);
Look at the manual. Changing <pre> tags to <code> should be as simple as:
$str = '<pre lang="php">
echo "test";
</pre>
<pre lang="html4strict">
<div id="test">Hello</div>
</pre>';
require_once("simplehtmldom/simple_html_dom.php");
$html = str_get_html($str);
foreach($html->find("pre") as $pre) {
$pre->tag = "code";
$pre->lang = null; // remove lang attribute?
}
echo $html->outertext;
// <code>
//     echo "test";
// </code>
// <code>
//     <div id="test">Hello</div>
// </code>
PS: you should encode the ", < and > characters in your input.
Just replacing pre tags with code tags changes the meaning and the rendering essentially and makes the markup invalid, if there are any block-level elements like div inside the element. So you need to revise your goal. Check out whether you can actually keep using pre. If not, use <div class=pre> instead, together with a style sheet that makes it behave like pre in rendering. When you just replace pre tags with div tags, you won’t create syntax errors (the content model of div allows anything that pre allows, and more).
Regarding the lang attribute, lang="php" is incorrect (by HTML specs, lang attribute specifies the human language of the content, using standard language codes), but the idea of coding information about computer language is good. It may help styling and scripting later. HTML5 drafts mention that such information can be coded using a class name that starts with language-, e.g. class="language-php"' (or, when combined with another class name,class="language-php pre"'.

PHP MySql display returned content without html tags being stripped

I have a column in SQL 'Text' datatype and inside I have content within html tag, eg somecontent: onetwo... I want the mysql query to echo out the databases contents without stripping the html tags (its possible this is done by php for security reasons or?) so that the html code will render if you get me? At the moment it just lumps out a paragraph which looks aweful! It should be noted security is not much of a concern as this is a project and not going to be exposed publicly
Cheers folks
Nick
MySQL wouldn't strip tags from text - it couldn't care less what the text is. PHP also wouldn't strip tags, unless somewhere in your code you do a strip_tags() or equivalent.
If you want to force the browser to display the tags in the retrieved data, you can run the string through [htmlspecialchars()][1], which converts html metacharacters (<, >, ", &, etc...) to their character entity equivalents (<, >, etc...).
Or you can force the entire page to be rendered as plain text by doing
header('Content-type: text/plain');
Database content isn't stripped by PHP unless you explicitly tell it to.
Are you sure your tags haven't been stripped before they were inserted?
Alternatively try stripslashes();
Use htmlspecialchars_decode() function. Its works fine for me...
Use guideline
Your Text with code
<?php
$text = "
<html>
<head>
<title>Page Title</title>
</head>
<body>
Reference site about Lorem Ipsum, giving information on its origins, as well as a random Lipsum generator.
</body>
</html> ";
OR
$text = $row['columnname']; // Here define your database table column name.
echo htmlspecialchars_decode($text);
?>
Output:
Reference site about Lorem Ipsum, giving information on its origins, as well as a random Lipsum generator.
this works for me:
Ex:
<?=htmlspecialchars_decode(htmlspecialchars('I <b>love</b> you'))?>
Your browser will output:
I love you
Use bellow snippet:
echo(strip_tags($your_string));
copied.

Categories