I have 1 javascript file which only contains Associative arrays.(This file will be generated by a testing tool, so no changes in this r allowed). I need to use the values of that array in php file so that i can store these values in DB. Please Specify how to do this?
-
1JavaScript will not run until after PHP if you put it on the same page. PHP executes on the server side before the page is returned to the clients web browser. Look into using AJAX and calling a PHP script to store the data through this. You will need to add some additional JavaScript to make the AJAX call. Using jQuery will make this easier.Ren– Ren2012-10-10 08:43:23 +00:00Commented Oct 10, 2012 at 8:43
-
@Ren — Nobody said anything about a "page". The JS is in a file.Quentin– Quentin2012-10-10 08:46:31 +00:00Commented Oct 10, 2012 at 8:46
-
@Quentin - I assumed when they said that the JavaScript file will be generated by a tool that the generated file would be included on a page. I don't see anything that contradicts this assumption. Certainly there are other ways to do it though.Ren– Ren2012-10-10 08:50:52 +00:00Commented Oct 10, 2012 at 8:50
2 Answers
PHP can run JavaScript via the V8 engine, although you will probably have to install it. You can use that to execute your JavaScript and (hopefully) extract the data.
Alternatively, write a web page that loads the JavaScript and then submits the data in it to a PHP script via Ajax.
2 Comments
Your best bet is to use JSON. PHP does not support Javascript by itself, but JSON is a common subset of Javascript that many platforms understand (which means it will be more widely supported if you need to reuse this data elsewhere).
In particular, you read the string from the file and then use json_decode:
$json_str = file_get_contents("json_file.js");
json_vals = json_decode($json_str);
Based on your comment:
<?php
$json_orig = <<<'json_oend'
var mime_samples =
[ {
'mime': 'application/xhtml+xml',
'samples': [{
'url': 'demo.testfire.net/',
'dir': '_m0/0', //it is for show trace
'linked': 2,
'len': 9645 }] },
{
'mime': 'text/html',
'samples': [{
'url': 'demo.testfire.net/.htaccess.aspx--\x3e\x22\x3e\x27\x3e\x27\x22\x3csfi000??001v275174\x3e',
'dir': '_m1/0', //it is for show trace
'linked': 2,
'len': 34 }] } ];
json_oend;
$json_str = preg_replace("/var[^=]*=/m", "", $json_orig);
$json_str = preg_replace("/;.*/m", "", $json_str);
$json_str = preg_replace("/'/m", "\"", $json_str);
$json_str = preg_replace("/\\/\\/.*/", "", $json_str);
$json_str = preg_replace("/\\\\x/", "\\u00", $json_str);
$json_val = json_decode($json_str, true);
for($i=0; $i<count($json_val); ++$i)
{
$samples = $json_val[$i]["samples"];
for($j=0; $j<count($samples); ++$j)
{
echo "$i.$j\n";
echo $samples[$j]['url'];
echo "\n";
}
}
?>