Storing HTML file as a PHP string - php

I have a full HTML page:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Template</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
...
</head>
<body>
...
</body>
</html>
I'm trying to save it in a variable like so:
$template = htmlentities("<!DOCTYPE HTML><html lang="en-US">...", ENT_HTML5, "UTF-8" );
.. but it chokes at just the first HTML tag.

That's because the first HTML tag has double quotes, just like you use for delimiting your string literal.
$template = <<<EOD
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Template</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
...
</head>
<body>
...
</body>
</html>
EOD;

You are not escaping the string propertly Try to:
Replace
htmlentities("//whatever your html code is//");
with
htmlentities('//whatever your html code is//');

user addslashes function..it will not truncate your string in between.
This function can be used to prepare a string for storage in a database and database queries.
Before storing into database or for any purpose
$final_string = addslashes('<!DOCTYPE HTML>
..........');
Before rendering that output on browser
$normal_string = stripslashes($database_retrived_string);

$data = '<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Template</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
...
</head>
<body>
...
</body>
</html>';
base64_encode($data);

Try this:
$temp = addslashes('<!DOCTYPE HTML><html lang="en-US">...', ENT_HTML5, "UTF-8" );
$template = htmlentities($temp);

Related

How to edit head tag in PHP with DOM with only DOMDocument

Just trying to edit/modify the head tag in order to add something inside with DOM and PHP.
$dom = new DOMDocument();
$dom->loadHtml(utf8_decode($html), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
for($i=0; $i<count($r);$i++)
{
// Prepare the HTML to insert
Here I want to add $var inside head tag (at the end if possible)
}
return $dom->saveHTML();
Everytime I tried, I have LENGHT=0 as the result of var_dump.
Edit: I don't want to edit an existing tag. I want to add a new one. To be more specific, I need to add OG meta tag for Facebook sharing.
Edit2 as requested :
Before
<head>
<meta blabla>
<title></title>
</head>
<body>
<h1></h1>
</body>
After
<head>
<meta blabla>
<title></title>
<meta new1>
</head>
<body>
<h1></h1>
</body>
But need to be edit via DOMDocument in PHP...
Add this to the top of your file:
<?php
$var = "Hello world.";
?>
Then start the HTML and add it there.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $var ?></title>
</head>
<body>
</body>
</html>
If you want to do it in PHP, you can try to use:
$titles = $domDocument->getElementsByTagName('title');
foreach($titles as $key => $title){
$title->setAttribute('attribute', 'value')
}
Source for the edit: https://stackoverflow.com/a/3195048/12077975
Try something along these lines:
$before=
'<html>
<head>
<meta name="old"/>
<title></title>
</head>
<body>
<h1></h1>
</body>
</html>
';
$HTMLDoc = new DOMDocument();
$HTMLDoc->loadHTML($before, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$xpath = new DOMXPath($HTMLDoc);
$destination = $xpath->query('//head/title');
$template = $HTMLDoc->createDocumentFragment();
$template->appendXML('<meta name="new"/>');
$destination[0]->parentNode->insertBefore($template, $destination[0]->nextSibling);
echo $HTMLDoc->saveHTML();
Output:
<html>
<head>
<meta name="old">
<title></title><meta name="new">
</head>
<body>
<h1></h1>
</body>
</html

Php variable not printing any value

In PHP I am writing:
$link = "<a href='/?s=cqs3&importo_desiderato=5000&categoria_cqs='. $cat .'>5.000€</a>";
But the value "$cat" is not showing anything.
Any suggestion?
Consider that if I write in HTML:
5.000€
It works...
Probably it is something I am missing in the sintax.
Thank you!
I solved like this:
<?php
$cat = $_GET['categoria_cqs'];//(to get the value from the session)
$link = "<a href='/?s=cqs3&importo_desiderato=5000&categoria_cqs=$cat'>5.000€</a>";
?>
I still cannot understand why I had to get it again (in HTML it worked without it) but that is fine. Thank you for your help!
The error is in the quotes, your line should look like this:
$link = '5.000€';
Remember that the string must be closed with the same quotation mark as it was opened.
Additionally, remember that the character " " and ' ' can "escape" themselves, as MoarCodePlz said.
I don't know what your real purpose is, if it is to create this directly in PHP or not, but maybe the code below will help you, I created a variable that will store the website URL that will pass the $cat variable as a parameter, to see the result I used the <a> tag in html
The code would look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
$cat = 'Pathname';
$link = "https://yourwebsite.com/?s=cqs3&importo_desiderato=5000&categoria_cqs=' . $cat . '";
?>
5.000€
</body>
</html>
If you want to get the result only in PHP, use the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
$cat = 'Pathname';
$link = "<a href='/?s=cqs3&importo_desiderato=5000&categoria_cqs=" . $cat . "'>5.000€</a>";
echo $link;
?>
</body>
</html>
Edit
You say that your code works only using HTML and not in PHP. Well, I've been analyzing it here and I saw that this was happening due to the fact that the file is in a directory, right? PHP was not understanding that the URL was from this directory, at least for me the error was this one in addition to the quotes
Please try the code below, I believe it will work in both PHP and HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
$cat = $_GET['categoria_cqs'];
$link = '5.000€';
echo $link;
?>
5.000€
</body>
</html>

pass variable via GET to decide if UTF-8 will be used

So the idea was this, if i use example.php?u=8, UTF-8 will be used.
I thought this would do the trick.
<?php
$u=($_GET["u"]); // 8 is utf8
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php if ($u=8): ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php else: ?>
<?php endif ?>
<title>just any title</title>
</head>
<body>
</body>
</html>
Obviously I am doing something completely, wrong, since it doesnt even give me the variable.
Where did i go wrong?

saveHTML() not working properly

I have this line of code in my index.php:
<?php include ("header.php"); ?>
</body>
</html>
My header.php:
<!DOCTYPE html>
<html lang="en">
<head>
<?php include("php/dynamic_header.php"); ?>
<meta charset="utf-8">
<meta name="description" content="Write a description" />
<meta name="keywords" content="Your keywords here" />
<title>Random Title</title>
</head>
<body>
<header>This is my header</header>
And my dynamic_header.php:
$dom = new domDocument;
#$dom->loadHTMLFile("header.php");
$meta = $dom->getElementsByTagName('meta')->item(1);
$meta->setAttribute('content','new description');
$dom->saveHTML();
However, when I use saveHTML(), nothing happens.
I tried using:
echo $dom->saveHTML();
But this produces two headers, so can someone explain me what am I doing wrong?
Basically, I'm trying to change attribute on my meta tag with PHP DOM, but I can't save it without duplicating my header.
It should work just as good with saveHTMLFile() which is why I believed something was wrong with your file permissions or so not allowing you to save back the data. Either way, I think you're doing this wrong you should use a template library instead of modifying the data with DOMDocument.
For example with Smarty, you could do a header template like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="{$description|default:"Write a description"}" />
<meta name="keywords" content="Your keywords here" />
<title>{$title|default:"Default Page Title"}</title>
</head>
<body>
Here was the relevant test code to show it would not create duplicates with DOMDocument:
<?php
$str = <<<DATA
<!DOCTYPE html>
<html lang="en">
<head>
<?php include("php/dynamic_header.php"); ?>
<meta charset="utf-8">
<meta name="description" content="Write a description" />
<meta name="keywords" content="Your keywords here" />
<title>Random Title</title>
</head>
<body>
<header>This is my header</header>
DATA;
$dom = new domDocument;
#$dom->loadHTML($str);
$dom->formatOutput = true;
$dom->preserveWhitespace = false;
$meta = $dom->getElementsByTagName('meta')->item(1);
$meta->setAttribute('content','new description');
echo $dom->saveHTML();

How to remove whitespaces from generated HTML?

FUNCTIONS.PHP
<?php
function global_header($page)
{
echo "
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>" . $page . "</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>
";
}
?>
<?php
function global_footer()
{
echo "
</body>
</html>
";
}
?>
When I view my page source in chrome/FF I get the following source:
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Add</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>
</body>
</html>
It's indented by about 3 tabs. Is there a PHP strip function or something that can align it properly? I don't like my entire pages HTML being messed up.
My expected output is to not be indented.
The reason you are getting indented outputs is that you are echoing them like that...
Simply remove the indentaions from the echo statements to get rid of them
<?php
function global_header($page)
{
echo "
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>" . $page . "</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>";
}
?>
<?php
function global_footer()
{
echo "
</body>
</html>";
}
?>
This makes your php harder to follow fut the output will be as you requested
Consider using a template engine. Direct output of HTML strings is considered bad practice.
If you don't want to use third-party template engines, you can anyway benefit from some simplified templating like this:
page.tpl template file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8' />
<title>{{title}}</title>
</head>
<body>
{{body}}
</body>
</html>
PHP:
// Loading HTML code that does not contain any undesired whitespace.
$code = file_get_contents('page.tpl');
// Replacing template variables with their values.
$code = str_replace(
array(
'{{title}}',
'{{body}}'
),
array(
'Example title',
'Page body'
),
$code
);
// Outputting resulting HTML code.
echo $code;

Categories