-3

I'm creating PHP scraper to get value from Javascript array, how to Convert Javascript array to PHP Array

<?php
// example scraped array
$str = 'var str_array = ["aa", "bb"]';
$str = str_replace("var ", '$', $str); 
eval($str);
print_r($str_array);
5
  • but js is client side after converting its not print of array using print_r Commented May 5, 2016 at 5:50
  • 1
    Possible duplicate of how to convert javascript array to php array Commented May 5, 2016 at 5:52
  • What are you trying to do? Commented May 5, 2016 at 5:53
  • Update eval($str); into eval("$str;"); Commented May 5, 2016 at 5:53
  • I need js string to process in the server, it not for client side. Commented May 5, 2016 at 5:54

2 Answers 2

4

Post your javascript array as a JSON string via ajax and process it server-side.

Javascript

var str_array = ["aa", "bb"];
var request = $.ajax({
  url: "test.php",
  method: "POST",
  data: { myData : JSON.stringify(str_array) },
  dataType: "html"
});
request.done(function( msg ) {
  // ajax response
});
request.fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});

PHP (test.php)

$json = $_POST['myData'];
$myDataArray = json_decode($json,true);
print_r($myDataArray);
1

Eval() should end with ;

<?php
$str = 'var str_array = ["aa", "bb"]';
$str = str_replace("var ", '$', $str); 
eval($str.";");
print_r($str_array);

Output:

Array ( [0] => aa [1] => bb )

But I don't know why you opt for this.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.