If you are attempting to print Javascript code to the page you'll want to convert all of the characters which are HTML characters to be their HTML Symbol equivalents. To do this we can use htmlspecialchars()
.
If you wanted the structure to persist, so that it looks like the code you pasted into the question you'll need to wrap it in the relevant HTML tag. In this case, that would be <pre>
. Previously, you could have also used <xmp>
but this is now deprecated and its use is discouraged.
Putting all of this together:
$snippet = "<script type='application/ld+json'>
{
'@context': 'http://schema.org',
'@type': 'WebSite',
'url': 'http://example.com/',
'potentialAction': {
'@type': 'SearchAction',
'target': 'http://example.com/index.php?page=search&sPattern={search_term_string}',
'query-input': 'required name=search_term_string'
}
}
</script>";
$htmlSnippet = "<pre>".htmlspecialchars($snippet)."</pre>";
This code does the following:
- Takes the code you want to use and assigns it to a variable (
$snippet
) as a string (taking care to ensure the quotes do not break the string enclosure).
- Converts the
$snippet
using htmlspecialchars()
- Concatenates the HTML tags
<pre>
and </pre>
around the output of htmlentities()
.
- Assign all of this to our
$htmlSnippet
PHP variable.
We could then echo this $htmlSnippet
variable and end up with the output in your question printed to the page without it being interpreted as HTML.
Notes:
- You might want to consider using the
<code></code>
HTML tag instead because then you are explicitly stating that what is contained in that element is code and not anything else. It will also, by default, display the code in a different font.
- You could use
htmlentities()
instead of htmlspecialchars()
depending on your circumstance. For more information check out this answer
Update:
After the update to your question, you appear to want to have this value returned by the function in your question. You would need to adjust your function to return this value as a string. Something like this would probably work:
function searchbox_markup(){
$baseUrl = "example.com";
$snippet = "<script type='application/ld+json'>
{
'@context': 'http://schema.org',
'@type': 'WebSite',
'url': '".$baseUrl."',
'potentialAction': {
'@type': 'SearchAction',
'target': '".$baseUrl."'index.php?page=search&sPattern={search_term_string}',
'query-input': 'required name=search_term_string'
}
}
</script>";
return $snippet;
}
To me, this looks messy. There is almost certainly a better way of solving the problem that you are trying to fix.