I am using fwrite to add javascript to a external script. In order to do this there needs to be a php string with the java inside. However the " and ' get mixed up and I am not sure how to fix it. Here Is the code:
$page =
"<script type="text/javascript">
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
function runit() {
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
mypre.innerHTML = '';
Sk.canvas = "mycanvas";
Sk.pre = "output";
Sk.configure({output:outf, read:builtinRead});
try {
eval(Sk.importMainWithBody("<stdin>",false,prog));
}
catch(e) {
alert(e.toString())
}
}
</script>
<?php
fwrite($fh, $page); ?>
The Script does what I want it to do, however the speech marks within the javascript mix with the php string speech marks as you can see above, causing the php to throw an error. Is there a way to fix this?
Thanks
-
1Escape your "s like this: \", or if you think that is dirty you can replace your "s with 's in your JS code.Andreas Argelius– Andreas Argelius2015年02月19日 10:07:57 +00:00Commented Feb 19, 2015 at 10:07
5 Answers 5
$page =
"<script type=\"text/javascript\">
function outf(text) {
var mypre = document.getElementById(\"output\");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles[\"files\"][x] === undefined)
throw \"File not found: '\" + x + \"'\";
return Sk.builtinFiles[\"files\"][x];
}
function runit() {
var prog = document.getElementById(\"yourcode\").value;
var mypre = document.getElementById(\"output\");
mypre.innerHTML = '';
Sk.canvas = \"mycanvas\";
Sk.pre = \"output\";
Sk.configure({output:outf, read:builtinRead});
try {
eval(Sk.importMainWithBody(\"<stdin>\",false,prog));
}
catch(e) {
alert(e.toString())
}
}
</script>";
<?php
fwrite($fh, $page);
?>
Comments
use here doc like so:
$page = <<<EOF
<script type="text/javascript">
.....enter the rest of the code here...
</script>
EOF;
echo $page;
find a manual to learn how to use heredoc
Comments
Use "''", or '""', or "\"\" " to escape the strings.
Comments
This is another way which is some kind comfortable and beautiful for you will keep overview, syntax highlighting and don't have to fight with the quotes:
<?php
ob_start(); // start output buffering
?> <!-- mark that there is no more php following, but HTML -->
<!-- copy your js here (without the very first quotes) -->
<script type="text/javascript">
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
// ............
</script>
<?php
$script = ob_get_contents();
ob_end_clean();
fwrite($fh, $script);
this will write your js to the file