xxxi have the_title() that returns some text, in this case Blue & Whiny
the problem as we can see is that the & character looks different
how do i turn Blue & Whiny into Blue & Whiny i tryed: htmlspecialchars_decode(the_title()), html_entity_decode(the_title()),htmlspecialchars(the_title()) and nothing.
i want to convert & to &
there is not much code to share, I just do this: <?php the_title() ?> and i get Blue & Whiny. If i use get_the_title() it wont display anything
Any ideas?
Thanks
edit1. ill share some code:
<script type="text/javascript">
function showShareUI() {
var act = new gigya.services.socialize.UserAction();
act.setUserMessage("Check out this article.");
act.setTitle("Trends on Explore Talent - <?php the_title(); ?>");
act.setDescription("<?php get_the_content(); ?>");
act.setLinkBack("<?php the_permalink(); ?>");
act.addActionLink("Check out this article", "<?php the_permalink(); ?>");
var image = {
src: 'http://xxx.com/wp-content/uploads/2011/05/BOTTOM_BANNER.jpg',
href: '<?php the_permalink();?>',
type: 'image'
}
act.addMediaItem(image);
var params =
{
userAction: act, // The UserAction object enfolding the newsfeed data.
onError: onError, // onError method will be summoned if an error occurs.
onSendDone: onSendDone // onError method will be summoned after
,showEmailButton: true
// Gigya finishes the publishing process.
};
gigya.services.socialize.showShareUI(conf, params);
}
function onError(event) {
alert('An error has occured' + ': ' + event.errorCode + '; ' + event.errorMessage);
}
function onSendDone(event)
{
document.getElementById('status').style.color = "green";
document.getElementById('status').innerHTML = 'The newsfeed has been posted to: ' + event.providers;
}
</script>
I've tried everything. This starts to annoy me...
html_entity_decode() is the correct way to do it.
html_entity_decode("Blue & Whiny");
Will produce:
Blue & Whiny
If it's not working, make sure you don't have another issue - such as passing a string to it that is double encoded, or running htmlentities() on the string again later.
Demo: http://codepad.org/BHXGWXJi
Double check with a literal string and var_dump() the output, you should see the decoded version. Then var_dump(the_title()), to make sure you are actually passing what you think you are to html_entity_decode().
html_entity_decode should do the trick. If not, try to specify the third parameter $charset.
Something like:
echo html_entity_decode(the_title(), ENT_QUOTES, 'UTF-8');
the_title() directly prints the title, so adding html_entity_decode() directly around that won't work. You can, however, stop it from printing with its third function argument. E.g.
<?php echo html_entity_decode(the_title('', '', false)) ?>
There's also get_the_title(), which doesn't directly print the title, but it requires the ID of the post you want the title of, in contrast with the_title, which prints the title of the current post in The Loop. So you need to do something like this:
<?php echo html_entity_decode(get_the_title($post->ID)) ?>
And actually, you should be able to simply do:
<?php echo $post->post_title ?>
The only reason these utility functions are there is to escape things for you and add tags and stuff. If you just want the raw input, you can print it directly.
This won't fix all of your issues, though, because you're echoing it inside a JavaScript string, so you need to escape certain characters. json_encode() should do the trick, but see the question "Pass a PHP string to a Javascript variable (including escaping newlines)" for more details.
Try this:
echo(mb_convert_encoding(the_title(), "UTF-8", "HTML-ENTITIES"));
see if this works for ya
$convmap = array (0x0, 0xffff, 0, 0xffff);
//$str = mb_decode_numericentity (the_title(), $convmap, 'UTF-8' );
$str = mb_decode_numericentity ("&", $convmap, 'UTF-8' );
echo $str;
http://www.php.net/manual/en/function.mb-decode-numericentity.php
Related
Am I doing this correctly? As I understand it, if I define the "return" value as true when I call print_r, it should return a string. I have the following function:
function alert($string) {
echo '<script>alert("' . $string . '");</script>';
}
And when I pass that function a regular old quote-encapsed string, it works just fine and dandy, but when I feed it this:
alert(print_r($array,true));
Nothing happens and I don't see an error, yet echoing print_r($array,true) works. Thanks for any help you can offer, I'm just trying to understand what's going wrong here even though it is obviously a very minor problem.
Use
<script>
alert(<?php echo json_encode(print_r($array, true)); ?>);
</script>
instead. Note the use of json_encode - this is to prevent any ' or other JS-metacharacters from introducing a JS syntax error, e.g.:
<?php
$name = "Miles O'Brien"; // note the '-quote in there
?>
<script>
alert('<?php echo $name ?>');
</script>
would give you:
alert('Miles O'Brien');
^-- start of string
^--end of string
^^^^-- unknown variable/function.
Your alert function has two problems handaling that input.
first, as metioned, your JS is missing qutes.
Second, the new lines should be converted to the string '\n'. otherwise your call to the alert function (in the js) will end in another line, which is not correct. for example:
alert("hello
world");
is invalid syntax.
so, this alert function will probably work:
function alert($string) {
$string=preg_replace('/\n/m','\\n',$string);
echo '<script>alert("' . $string . '");</script>';
}
print_r (as well as var_dump) outputs its content to stdout. However, you can control this behaviour with PHP's buffers.
Have a look at What is output buffering?, then http://www.php.net/manual/en/ref.outcontrol.php.
I currently have a webpage that need to use javascript to parse variables from php.
I do things like this:
data.notices = JSON.parse('<?php echo json_encode($notices) ?>');
However, when there is single or double quotes in the $notices variable, javascript console return errors.
How can I get the variables correctly?
This code doesn`t return error
<?
$notices = array('sad'=>'asd as" asd', 'asd"sdf '=>'asdasd" \' asd ads');
?>
<script>
data = new Object();
data.notices = JSON.parse('<?php echo addslashes(json_encode($notices)) ?>');
</script>
$a='b' will be converted to "b"(note the quotation mark) by json_encode
just write JSON.parse(<?php echo json_encode($notices) ?>);(remove ') will be ok.
I found that it is the problem caused by the fact that I did not escape the characters before inserting to database.
You are one extra operation. If you want message as javascript variable you can directly get like
data.notices = <?php echo json_encode($notices) ?>;
// and access like this
// data.notices[0] or data.notices['alert']
I have one page iframed inside of another. The child page communicates with the parent page by using the sendMessage() function. The parent page runs eval() on the message that is received from the child page.
This is the code that constructs the message:
var msg_string = '$("body").append("<?php echo $content; ?>")';
var send_string = "sendMessage(\'" + msg_string + "\', '<?php echo $receiver_domain; ?>')";
setTimeout(send_string, <?php echo $delay; ?>);
The problem among other things is that the $content variable contains HTML and the double quotes in things like id="test" do not play well with all of this concatenation. I am at a loss trying to figure this out.
I have already attempted to escape the quotes in $content by converting them to " but that resulted in the browser placing div ids in double double quotes (""test"").
** Update **
Using the json_encode method does work for getting the data to the parent page. It's a much easier solution than what I had been doing (I had already accomplished this much but figured something was amiss). That said, the eval of the data still fails if there are double quotes in a div id="test". A string of just "test" works, but it actually puts "test" verbatim. This is the javascript source in the html after using the json method:
var msg_string = '$("body").append("<div class=\\\"test\\\">HEY WHATS UP<\/div>");';
var send_string = "sendMessage(\'" + msg_string + "\', 'http://domain.com')";
setTimeout(send_string,500);
This fails at the eval. Putting an alert in place of the eval yields this:
$("body").append("<div class="test">HEY WHATS UP</div>");
Any ideas?
** Update 2 **
So I FINALLY figured this out. It was a combination of the three answers below. The json answer tipped me off. Basically the double quotes needed to be tripple backslashed so that by the time it go to the eval, everything would be read properly.
I ran into a few other snags, including /r/n characters in the html...which I removed with str_replace and also an apostrophe...which was in an inner html element...I replaced that with the appropriate html entity and BAM!
Here is the code:
function escapeQuotes(string){
var quotes_regex = new RegExp("\"", "g");
return string.replace(quotes_regex, "\\\"");
}
var msg_string = '$("body").append(<?php echo json_encode( str_replace("\r\n", '', $content) ); ?>);';
var send_string = "sendMessage(\'" + escapeQuotes(msg_string) + "\', '<?php echo $receiver_domain; ?>')";
setTimeout(send_string,<?php echo $delay; ?>);
I upvoted everyone's answer since I used bits of everything. Thank you so much!
JSON is your friend.
var msg_string = '$("body").append(<?php echo json_encode($content); ?>)';
If your only concern is double quotes, why not just replace them with an escaped string?
var msg_string = '$("body").append("<?php echo str_replace("\"", "\\"", $content); ?>")';
I can't exactly test, but that would seem to work to me.
You need to escape using str_replace
$search = array("'", '"');
$replace = array("\'", '\"');
var msg_string = '$("body").append("<?php echo str_replace(search, replace, $content; ?>")';
lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:
onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....
and it results in
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same.
How to escape any string so that it won't ruin javascript?
json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:
http://img402.imageshack.us/img402/5577/aaaahf.gif
and I did used:
('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) {
The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:
<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';
That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
Your problem is highlighted in bold.
You can't quote a variable declaration
you shouldn't need to escape the double quote once this is removed since it is within single quotes.
Should look like this -
onclick="newFunc();"
<script>
function newFunc() {
var a = prompt('New value: ', 'aaaa"aaa');
if (a != null) { v....
}
</script>
...onclick="new_func();"...
<script>
function new_func() {
var a = prompt('new value:','<?php code; ?>');
if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
I'm really just re-wording what #Marshall House says here, but:
In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that #Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.
E.g.:
<script>
// This is a function, wrapping your code to be called onclick.
function doOnClickStuff() {
// You should no longer need to escape your string. E.g.:
//var a = prompt('new value:','<?php echo $rec[$i]; ?>');
// Although the following could be safer
var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
if (a) { <!--javascript code--> }
else { <!--javascript code--> }
}
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
<a onclick="run('Hi, Tim! I've got two', '">test</a>
The onclick event is not run at all.
The above is generated by something like this:
<a onclick="run(<?php echo htmlentities($str) ?>)">test</a>
How to fix it?
You are outputting the content of a string without quoting it
Put the echo statements in ''
<a onclick="run('<?php echo htmlentities($str) ?>')">test</a>
By the way, ' = '
$str, before being entity-encoded, is:
'Hi, Tim! I've got two', '
which is clearly not a valid JavaScript string literal. The apostrophe is HTML-encoded, which it shouldn't be yet, and there's some trailing nonsense.
You should create JavaScript string (and other) literals using the json_encode function. If you have $rawstr as:
Hi, Tim! I've got two
then json_encode will give you the correct JavaScript string:
'Hi, Tim! I\'ve got two'
so you can insert it into an HTML event handler attribute:
<a onclick="run(<?php echo htmlspecialchars(json_encode($rawstr)) ?>); return false;">test</a>
Note htmlspecialchars(), which is preferable to htmlentities(), as the latter will usually-needlessly HTML-escape all non-ASCII characters, which will mess them up if you don't specify the correct charset.
From PHP 5.3, you can use the JSON_HEX_ flags to ensure that the HTML-special characters are never in the output from json_encode, which saves you an encoding step:
<a onclick="run(<?php echo json_encode($rawstr, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT) ?>); return false;">test</a>
To make your life easier, encapsulate these common output-with-escaping methods into more simply-named functions:
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
function j($s) {
echo json_encode($s, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_HEX_APOS);
}
function u($s) {
echo urlencode($s);
}
<a onclick="run(<?php j($rawstr); ?>); return false;">test</a>
And even better, avoid using inline event handler attributes at all by binding from script:
<a id="test">test</a>
...
<script type="text/javascript">
document.getElementById('test').onclick= function() {
run(<?php j($rawstr); ?>);
return false;
};
</script>