Reputation: 133
I have an generated output.js file from a specific device which contains Array in it:
var OUT=new Array (0x80,0x00,0x40,0x0026,0x0011,0x0014,0x0013,0x0018,0x0017,0x03FD,0x0116)
How can i get access to this array with PHP, so i can easily print specified Array[x] in any location:
print $OUT[4];
With simple JS i was able to do it like:
document.write(OUT[4]);
In case i can also handle that output.js with PHP like a txt file and then splitting and "doing like array thing" but i think there is away to use it right.. ^_^
Any tips or suggestions on that ? :)
Thnx!
Upvotes: 0
Views: 138
Reputation: 453
Easiest way is to use a library like jQuery rather than roll your own...
<head>
<script src="http://code.jquery.com/jquery.min.js">
....
Then at the point you calculate your data, post it to PHP server
var OUT = new Array (0x80,0x00,0x40,0x0026,0x0011,0x0014,0x0013,0x0018,0x0017,0x03FD,0x0116);
$.ajax({
url: 'http://www.example.com/receiver.php' //change example.com to your server
,type: 'POST' //use POST so don't have to worry about URL length
,data: {out: OUT} //pass contents of 'OUT' in variable 'out'
,dataType: 'json' //use JSON formatting of data
,error: function() {
alert("Failed to contact server");
}
,complete: function() {
alert("Finished sending data to server.");
}
});
In receiver.php
$OUT = json_decode( $_POST['out'] ); // 'out' matches the parameter name in jQuery Ajax call
print_r( $OUT ); //print contents of array $OUT
Upvotes: 0
Reputation: 943142
If you want to fetch the file directly with PHP then you can either write a custom parser (using regular expressions if you can trust the file format to be consistant) or by interfacing with a JavaScript engine.
Otherwise, assuming the JavaScript is running in a web browser…
The simplest way to do this would be to make use of createElement
and appendChild
while looping over an array to create a form
element containing a hidden
input for each element of the array (with a name such as foo[]
to satisfy the algorithm PHP uses to populate $_POST
and friends) and then submit()
the form.
Alternatively, you could serialise the array to a string (e.g. a comma separated one if you know that there are no commas in the data) and create a query string with it (var qs = "?foo=" + encodeURIComponent(serialised_array);
) and then pass it using XMLHttpRequest.
Upvotes: 2
Reputation: 3065
you can use json for doing this
var jsonString = JSON.stringify(OUT);
then
document.getElementById('IdOfYourFormInputField').value = jsonString;
// make element type hidden
now when you submit the form you will get the json string in $_POST field
so you can decode it like
$phpArray = json_decode($_POST['NameOfYoutInputEleMent']);
That's It!!!
Upvotes: 0