Ruf1
Ruf1

Reputation: 179

How Can I produce meta tag strings in PHP

I'd like to produce my meta tag lines in php and then echo them in the of the page. I seem to be having problems. When I echo the variable it actually echo's on screen rather than be contained to view source only like the other meta tags.

$ogmeta = '<meta property="og:type" content="Article" />';

then I was just doing

echo $ogmeta;

I also tried

$ogmeta = htmlspecialchars('<meta property="og:type" content="Article" />');

Each time it echos to screen :(

EDIT:

I found this to work

$ogmeta = '<meta property="og:title" content="'.$title.'" />'; 
echo $ogmeta;

But I need to have multiple entries for $ogmeta like this:

$ogmeta = '';
$ogmeta .= '<meta property="og:title" content="'.$title.'" />';
$ogmeta .= '<meta property="og:site_name" content="some site" />';
$ogmeta .= '<meta property="og:type" content="Article" />';
$ogmeta .= '<meta property="og:url" content="'.$which_article.'" />';

When I tried echoing this it all appeared on a single line. I tried adding a line break but that doesnt work. Any ideas?

Upvotes: 0

Views: 17101

Answers (3)

You can also do like this. Inserting your PHP inside the <meta> tags too.

<?php
$metaKeywords="books,cars,bikes";
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title>SomePage</title>
<meta name="description" content="<?php echo 'somedescription' ?>"></meta>
<meta name="keywords" content="<?php echo $metaKeywords ?>"></meta>
</head>

EDIT:

Solution 1: Make use of HEREDOC, Its pretty easier.

<?php
$metaTag=<<<EOD
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title>SomePage</title>
<meta name="description" content="my description here"></meta>
<meta name="keywords" content="cars,bikes,books"></meta>
</head>
EOD;
echo $metaTag;
?>

Solution 2: You can also embed variables inside the HEREDOC.

<?php
$metaDesc="this is new";
$metaKeywords="cars,bikes,thrills";
$metaTag=<<<EOD
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title>SomePage</title>
<meta name="description" content=$metaDesc></meta>
<meta name="keywords" content=$metaKeywords></meta>
</head>
EOD;
echo $metaTag;//Don't forget to echo
?>

Upvotes: 1

Ruddy
Ruddy

Reputation: 9923

$ogmeta = "property='og:type' content='Article'";


<meta <? echo $ogmeta; ?> />

Could do that?

Leave the meta tag always there and just fill in the gaps.

Next best:

$ogmeta = "<meta property='og:type' content='Article' />";

echo "$ogmeta";

This should work.

Upvotes: 0

Quentin
Quentin

Reputation: 943185

If you want <something> to be treated as a tag, then represent < and > as < and > (which are the HTML characters for start of tag and end of tag) and not as &lt; and &gt; (which are the HTML entities for less than and greater than).

$ogmeta = '<meta property="og:type" content="Article">';

Upvotes: 1

Related Questions