0

Possible Duplicate:
unterminated string literal

I have a problem setting og:description with followed function...

function createFacebookMeta($title, $fcUrl, $fcImg, $fcDesc){    
    $fcDesc = (strlen($fcDesc) > 100) ? substr($fcDesc,0,150).'...' : $fcDesc;
    $faceBook = "<script type=\"text/javascript\">


$(document).attr('title', '".$title."');
$('meta[property=\"og:title\"]').attr('content', '".$title."');
$('meta[property=\"og:url\"]').attr('content', '".$fcUrl."');
$('meta[property=\"og:image\"]').attr('content', '".$fcImg."');
$('meta[property=\"og:description\"]').attr('content', '".$fcDesc."');
FB.XFBML.parse();
</script>";
echo $faceBook;
}

as response i get in firebug

unterminated string literal

 $('meta[property="og:description"]').attr('content', 'Logos gedruckt<br />  //breaks here

even if i use striptags it reports same ... if i don´t set og:description default meta description is taken (np here) which is about the same lenght, as i read that fb takes arround 300 chars from it max

thank you

$fcDesc is db result

$fcDesc = "Logos gedruckt
<br>
100% Baumwolle
<br>
Vorne: Logo
<br>
Rücken: Cash Ruls";

(product description)

Community
  • 1
  • 1
manga
  • 105
  • 1
  • 8

1 Answers1

1

You are outputting strings into javascript code in a way that it breaks the code.

That happens because you do not properly encode the PHP values for javascript.

An easy way to do that is to use the json_encode() function:

$faceBook = '<script type="text/javascript">
$(document).attr(\'title\', ' . json_encode($title) . '); ....';

Use it whenever you need to encode the value of a PHP variable for javascript. JSON is a subset of javascript so this works really well.

Additionally you might want to simplify the description string:

$simplified = preg_replace('/\s+/', ' ', strip_tags($fcDesc));

This does remove the HTML <br> tags you have in there and then normalizing whitespaces.

Also let's see json_encode in action:

echo json_encode($simplified), "\n";

Output:

"Logos gedruckt 100% Baumwolle Vorne: Logo R\u00fccken: Cash Ruls"

As you can see, json_encode takes not only care of adding the quotes but to also properly encode characters in the string into unicode sequences.

In your original string you had line-breaks. In javascript you can not have line-breaks in string (you can have in PHP, but not in javascript). Using json_encode on your original string does fix that, too:

"Logos gedruckt\n<br>\n100% Baumwolle\n<br>\nVorne: Logo\n<br>\nR\u00fccken: Cash Ruls"

As you can see, the line-breaks are correctly written as \n in the output. Just remember json_encode, use it for all your variables you put into the javascript tag. That will make your code stable.

hakre
  • 193,403
  • 52
  • 435
  • 836