I'm using PHP to create a JavaScript document. It does do two things:
Read a directory containing some HTML files that I use as templates and then output an object containing key: value pairs that represent the filename: content, which will end up similar to this:
var HTML = { "blogpost.html": '<div>{post}</div>', "comment.html" : '<div class="comment">{comment}</div>' };Which allows me to use
HTML["template.html"]to append templated data that I receive from AJAX requests.Read a directory containing JavaScript files and output the content of those straight into the document.
Locally it's working fine, but I've been getting this error when I try it once uploaded:
Uncaught SyntaxError: Unexpected token ILLEGAL
I've tried wrapping the output I get from each of the HTML and JS files in things like:
preg_replace('/\s{2,}/', '', $output);
addslashes($output);
mysql_real_escape_string($output);
And a combination of those, but still the same error.
How can I reliably output the HTML and JavaScript I'm trying to place in the output?
Here's the current entire PHP script I am using (which works locally but not online weirdly):
header("Content-type: application/x-javascript");
// Write HTML templates.
$dir = dir($_SERVER['DOCUMENT_ROOT'] . '/view/html/');
$files = array();
while($file = $dir->read())
{
if(strpos($file, ".html"))
{
$key = substr($file, 0, strpos($file, ".html"));
array_push($files, '"' . $key . '": \'' . compress(file_get_contents($dir->path . $file)) . "'");
}
}
echo 'var HTML = {' . implode(",", $files) . '};';
// Output other JavaScript files.
$js = array();
array_push($js, file_get_contents("plugin/jquery.js"));
array_push($js, file_get_contents("plugin/imagesloaded.js"));
array_push($js, file_get_contents("plugin/masonry.js"));
array_push($js, file_get_contents("base/master.js"));
array_push($js, file_get_contents("plugin/ga.js"));
echo implode("", $js);
// Compress a JavaScript file.
function compress($str)
{
return addslashes(preg_replace('/\s{2,}/', '', $str));
}