saveHTML() not working properly - php

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();

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

joomla 3.x - how to include "metadescription" and "title" in the header without using <jdoc:include type="head" />

I am trying to get more control over the header of my Joomla site; for some pages I don't need many things in the header. I decided to make a template where I don't use the <jdoc:include type="head" />, because it loads lot of things that I don't need.
Searching, I found this old post about the subject, and in the web some people looking for the same thing. Manually control <head> markup in Joomla
I was wondering if it is possible to add to my index.php template file to PHP code that could get just the "metadescription" and the "title" of the Joomla publication. Something like this:
<?php defined( '_JEXEC' ) or die; ?>
<!doctype html>
<html lang="<?php echo $this->language; ?>">
<head>
<meta name="viewport" content="width=device-width />
<meta name="description" content="<?php echo **code metadescription** ?>" />
<title><?php echo **code to get title** ?></title>
</head>
<body>
<jdoc:include type="component" />
</body>
</html>
Nice, after while i could find the code that i was looking for, and maybe it could help others, it worked for me... in the index.php file of the template i added:
<?php defined( '_JEXEC' ) or die;
$doc =JFactory::getDocument();
$meta_description = $doc->getMetaData("description");
$title = $doc->getTitle();
?>
<!doctype html>
<html lang="<?php echo $this->language; ?>">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<meta name="description" content="<?php echo "$meta_description"; ?>" />
<title><?php echo "$title" ?></title>
</head>
<body> <jdoc:include type="component" /> </body>
</html>
Just use PHP include() function
In top.php
<meta name="viewport" content="width=device-width />
<meta name="description" content="<?php echo **code meta description** ?>" />
<title><?php echo **code to get title** ?></title>
And in your current file just include the file(top.php) like
<?php defined( '_JEXEC' ) or die; ?>
<!doctype html>
<html lang="<?php echo $this->language; ?>">
<head>
<?php include("top.php"); ?>
</head>
<body>
<jdoc:include type="component" />
</body>
</html>
I don't know if this is a good way, but you can unset all css and js in the following style:
unset($doc->_styleSheets[$this->baseurl.'/path/to/some.css']);
unset($doc->_scripts[$this->baseurl.'/path/to/some.js']);
I recommend not to remove meta tage like content-type or x-ua-compatible. These tags support your website in some browsers. And the favicon link is helpful by bookmarks.

Storing HTML file as a PHP string

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);

HEAD section in a PHP include

I work with PHP includes, and I need to put HEAD information in one of them. Is this possible, or can I only put a HEAD section on top of the index.php?
I'm asking this because the PHP includes has queries which I need in order to get OG image data (for social media) into the head. For example: I have a file WEBSHOP.PHP and in this file there is a product with an image. I want that image to show on the timeline in FaceBook.
This is an example of my (shortened version) of index.php:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<? include webshop.php; ?>
</body>
This is an example of my (shortened version) of webshop.php:
<!-- some mysql query to get variables as $pic and $row->meta_title -->
<head>
<meta property="og:image" content="http://forteuitgevers.nl/images/boeken/<? echo $pic; ?>" />
<meta property="og:title" content="<? echo $row->meta_title; ?>" />
<meta property="og:description" content="<? echo $row->meta_des; ?>" />
<meta property="og:url" content="http://<? echo $_SERVER['HTTP_HOST']; ?>/<? if (!empty($url_array[1])) { echo $url_array[1]; echo '/' ; } ?><? if (!empty($url_array[2])) { echo $url_array[2] ; } ?>" >
</head>
<!-- some code to view the webshop item -->
You're going to have to change the structure of your PHP files a bit in order to get all the header tags into one <head> section. If you include the webshop.php file before you start generating your HTML output you can then access the PHP variables when you write the head section. Something like this:
index.php:
<?php include webshop.php; ?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<meta property="og:title" content="<?php echo $row->meta_title; ?>" />
<!-- other meta tags using variables from webshop.php -->
</head>
<body>
<!-- print out HTML code from webshop.php -->
<?php echo $doc_body; ?>
</body>
Then in webshop.php you'll have to save any HTML output with output buffering so you can add it into the HTML code in the proper place. Something like this:
<?php
// sql queries to get data
ob_start();
?>
<!-- html code to show up in the body section to view webshop items -->
<?php
$doc_body = ob_get_clean();
?>
Check out the PHP.net manual page on Output buffering for more info on ob_start and ob_get_clean.
Yes you can. However this is bad style. And you are making your HTML wrong:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<? include webshop.php; ?>
</body>
this will lead into
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<head>
<meta property="og:image" content="http://forteuitgevers.nl/images/boeken/<? echo $pic; ?>" />
<meta property="og:title" content="<? echo $row->meta_title; ?>" />
<meta property="og:description" content="<? echo $row->meta_des; ?>" />
<meta property="og:url" content="http://<? echo $_SERVER['HTTP_HOST']; ?>/<? if (!empty($url_array[1])) { echo $url_array[1]; echo '/' ; } ?><? if (!empty($url_array[2])) { echo $url_array[2] ; } ?>" >
</head>
</body>
However HTML does not like that the head tag is inside of the body tag. But most browser will still show it correctly.
To be sure: Check your result with a HTML Validator.

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