2

I need some javascript variables to be parsed in order to be updated onto an SQL database.

1) How would I parse this lines directly from the source code for example:

//our variables
var y = "bloblo";
var x = "blabla";
var z = "bleble";

(this block above would be somewhere in the source code of the page, and my objective is to retrieve it, and store it in some php variables) What would be the most appropriate way to do it?

2) Is there a way to directly access the source code of a website in order to use this parser and retrieve/save the data?

1
  • Can I use a callback function on a random webpage source ? Commented May 24, 2014 at 9:18

2 Answers 2

1

This function does a basic parsing of a JS source to find variable definitions:

function parse_js_vars($source) {
    $res = array();
    $matches = array();
    $rx = "/(?:var)?\s+([\$A-Za-z_][$\w]*)\s*=\s*['\"]?([^'\";]*)[\"']?\s*(?:^|;)/";
    preg_match_all($rx, $source, $matches);
    foreach ($matches[1] as $n => $name) {
        $res[$name] = $matches[2][$n];
    }
    return $res;
}

Example:

parse_js_vars("var a=5;var b='hello';");

returns

array(
  "a" => "5"
  "b" => "hello"
)
Sign up to request clarification or add additional context in comments.

What is "[$\w]*" for? That I don't understand. Thanks for the regexp anyway.
[$\w] matches all letters, numbers, underscores and $ characters. This is to match every character that can be part of a variable name (but not the first character, that cannot be a number).
Isn't it alread done by "[\$A-Za-z_]" ?? Plus, shouldn't the short cut '\w' be outside of a class definition "[]"
0

Perform AJAX call using jQuery, for example:

$.ajax({
  type: "POST",
  url: "example.php",
  data: { y: y, x: x, z: z }
})
  .done(function( msg ) {
    // Perform changes on your page after AJAX request succeed.
    alert( "Data Saved: " + msg );
  });

You PHP server part, will be able to parse then:

$y = filter_input(INPUT_POST, 'y');
$x = filter_input(INPUT_POST, 'x');
$z = filter_input(INPUT_POST, 'z');

I was actually looking for away to avoid this situation cause ajax is not cross domain, and what I need is to get the data from the source of a site that I don't own.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.