Escaping escaped characters in PHP

Associate
Joined
30 Dec 2005
Posts
415
The following Javascript code is generated by PHP..
Code:
div = document.getElementById('contentdiv');
div.innerHTML ="<div class="trigger" onClick="showBranch('branch1')">Day 1</div>
		<span class="branch" id="branch1">
		<a href="1">Leg 1</a><br /><a href="2">Leg 2</a><br /><a href="3">Leg 3</a><br />
";

Now I'm guessing that all the double quotes should be escaped like
Code:
div = document.getElementById('contentdiv');
div.innerHTML ="<div class=\"trigger\" onClick=\"showBranch('branch1')\">Day 1</div>
		<span class=\"branch\" id=\"branch1\">
		<a href=\"1\">Leg 1</a><br /><a href=\"2\">Leg 2</a><br /><a href=\"3\">Leg 3</a><br />
";
However, I'm not sure how to do this in PHP, as all of those double quotes have already been escaped..
PHP:
$data .= "	<div class=\"trigger\" onClick=\"showBranch('branch".$dayid."')\">Day ".$dayid."</div>\n";

I know you cant use \\" as that will create a T-STRING error...

Can anyone point me in the right direction?
 
3?! That's just being greedy :p

However, it's still not liking it. FF returns an error: Unterminated string literal.
This is the code now produced:
Code:
div = document.getElementById('contentdiv');
div.innerHTML ="<div class=\"trigger\" onClick=\"showBranch('branch1')\">Day 1</div>
<span class=\"branch\" id=\"branch1\">
<a href=\"1\">Leg 1</a><br />
<a href=\"2\">Leg 2</a><br />
<a href=\"3\">Leg 3</a><br />";
 
I might have misunderstood what you're trying to achieve, but use Heredoc syntax to save on escaping in PHP. And then remove the new-lines from the JS innerHTML to get rid of the unterminated literal error:

Code:
$string = <<<JS
	div = document.getElementById('contentdiv');
	div.innerHTML = '<div class="trigger" onClick="showBranch(\'branch1\')">Day 1</div><span class="branch" id="branch1"><a href="1">Leg 1</a><br /><a href="2">Leg 2</a><br /><a href="3">Leg 3</a><br />';
JS;

Or if you wish to keep the multiple lines for your innerHTML assignment, then use + to continue to assignment over several lines:
Code:
$string = <<<JS
	div = document.getElementById('contentdiv');
	div.innerHTML = '<div class="trigger" onClick="showBranch(\'branch1\')">Day 1</div>'+
			'<span class="branch" id="branch1">'+
			'<a href="1">Leg 1</a><br /><a href="2">Leg 2</a><br /><a href="3">Leg 3</a><br />';
JS;
 
Back
Top Bottom