javascript variable parsing by php regex - php

I am trying to parse some javascript variables using PHP.
Random website: (not my website)
//.... content ...
function(response) {
if (response) {
var data = { id: "fka1q021", action: "post", date: "today" };
}
//.....
$url = 'www.website.com';
$content = htmlspecialchars(file_get_contents($url));
preg_match_all('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
print_r($matches);
Output:
Array ( [0] => Array ( ) [1] => Array ( ) )
I want to get value of id which is fka1q021
How can I get it? Thanks

You may want to try preg_match instead of preg_match_all. Then, the $matches array will contain the entire matched expression as its 0th element, and the match within your parenthesized sub-expression as its 1st element. That 1st element is the id you're looking for.
So, try:
preg_match('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
Here is full example code:
<?php
$content = <<<ENDOFCONTENT
//.... content ...
function(response) {
if (response) {
var data = { id: "fka1q021", action: "post", date: "today" };
}
//.....
ENDOFCONTENT;
preg_match('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
print_r($matches);
print "id = " . $matches[1] . "\n";
Here is resulting output:
Array
(
[0] => var data = { id: "fka1q021", action: "post", date: "today" };
[1] => fka1q021
)
id = fka1q021

You are not getting anything with your regular expression, because you are applying htmlspecialchars to the content you are reading – and that replaces " with ", so your expression does not find the " you have in there.
Just remove htmlspecialchars, and your pattern will match.

Javascript is client side and PHP is server side, so all the PHP will have executed before the Javascript can run. See this question: How to pass JavaScript variables to PHP?

I'm not sure what your doing is legit... JS ans PHP doesn't execute at the same time and in the same place. Maybe you got this after an ajax call ?
Anyway, analysing a JS data with php can be done with json_decode. I think your problem here will be that json_decode won't understand {id:"value"}, he needs {"id":"value"} instead...
if ( preg_match("#data = ({[^}]*})#",$data,$matches) )
json_decode($matches[1]) ;
For example,
print_r(json_decode('{"id":"fka1q021","action":"post","date":"today"}') );
Render a php object :
stdClass Object
(
[id] => fka1q021
[action] => post
[date] => today
)

A very simple regex is
(?:id:\s(\".*?\"))
Debuggex Demo
then the id will be in capture group 1.
Let me know if you need a more complex regex. And if so, provide more info.

Related

remove character from php key value array

This is the array i have right now. I want to remove the random open bracket in the [0] => ["A100" and also the random close bracket in [4] => "B11"] ....I ve tried using :
foreach($list as $key=>$value)
{
**//its suppose to be the same array that is $list not a new array $array**
$list[$key]=str_replace("[","",$value);
}
$list being the array that contains the pictured elements. It doesnt seem to remove the brackets.. Am I doing something wrong?
**UPDATE: **
Im getting the array from a localstorage sending it through post to another php where i catch the value and explode to a array called $list.
$(function(){
$('#fbtn').click(function(){
$.ajax({
url: 'FactorAnalysis.php',
type: 'POST', // GET or POST
data: {data: localStorage.getItem('reportArray')}, // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is"+ data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("failed");
}
});
});
});
the localStorage outputted to a div shows me :
so here im sending the data through a ajax call:
$list = array();
$list = explode(',',$_POST['data']);
^ then in another php (FactorAnalysis.php) i get the array and explode to array $list.
Try this
$list = json_decode($_POST['data'], true);
instead
$list = explode(',',$_POST['data']);

jQuery flot plugin data from SQL

I am currently using the jQuery plotting plugin (Click), but I am having trouble fetching the data out of my database.
I am using PHP for the SQL part, which returns an array like this:
Array (
[0] => 13
[id] => 13
[1] => 320.82
[real_value_1] => 320.82
)
Now I need it in the following format in order for the flot plugin to pick it up:
[13, 320.82]
But I am having trouble figuring out how.
This is the plotting code:
$(document).ready(function(){
var url = "view_json_graph.php?type=2";
$.get(url, function(data){
console.log(data);
$.plot($("#placeholder"), data, { yaxis: { max: 100 }, xaxis: { max: 100 } });
});
});
Where the javascript var data, would be the data returned ( [13, 320.82] ).
Could anyone please give me advice on how to do it? I've also looked into JSON, but I couldn't get it to work with JSON either.
You should simplify your array first, so it would only contain the values only once:
Array (
[0] => 13
[1] => 320.82
)
After that, you could use php's implode() function, to make your array into a string, separated by commas:
$result = '[' . implode( ',', $array ) . ']';
This will be your desired format.
Dont know whether the below code helps you
<?php
$sql = "SELECT id, value FROM sample";
$query = mysqli_query($connect, $sql);
while($res = mysqli_fetch_array($query))
{
$out[] = "[".$res[0].','.$res[1]."]";
}
$comma_separated = implode(",", $out);
echo $comma_separated;
?>

json with no index after unset encode array in php

I hope anyone can help me. My JSON isn't indexed (i.e. there isn't any key above any element)
[
{
"nome":"LABORGHINI GALLARDO",
"descrizione":"LAMBORGHINI GALLARDO ED. NERA- ANNO 2007- ",
"indirizzo_pubblicato":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/LABORGHINI GALLARDO31072013-023853.json",
"indirizzo_immagine_copertina":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/IMG_1414 (600x448).jpg",
"indirizzo_paginaauto":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/index.html"
},
{
"nome":"RENAULT MEGANE",
"descrizione":"RENAULT MEGANE -ANNO 2006-DIESEL-CC. 1461",
"indirizzo_pubblicato":"autocaricateeea\/RENAULT MEGANE31072013-024103\/RENAULT MEGANE31072013-024103.json",
"indirizzo_immagine_copertina":"autocaricateeea\/RENAULT MEGANE31072013-024103\/P1080949 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/RENAULT MEGANE31072013-024103\/index.html"
},
{
"nome":"FORD MONDEO",
"descrizione":"FORD MONDEO SINISTRATA- ANNO 2009- DIESEL- CC. 1997-",
"indirizzo_pubblicato":"autocaricateeea\/FORD MONDEO31072013-045216\/FORD MONDEO31072013-045216.json",
"indirizzo_immagine_copertina":"autocaricateeea\/FORD MONDEO31072013-045216\/P1080971 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/FORD MONDEO31072013-045216\/index.html"
}
]
but after running unset() to remove an element with PHP the output JSON appears like this:
{
"1": // <--- **** add a key before an element
{
"nome":"Fiat Punto ",
"descrizione":"Fiat Punto Bianca",
"indirizzo_pubblicato":"autocaricateeea\/Fiat Punto 14072013-042703\/Fiat Punto 14072013-042703.json",
"indirizzo_immagine_copertina":"autocaricateeea\/Fiat Punto 14072013-042703\/P1080713 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/Fiat Punto 14072013-042703\/index.html"
},
...........
...........
...........
How you can see there is a key before the element of JSON.
I know that this behavior is caused by unset (PHP json_encode as object after PHP array unset()).
There is a way to prevent this behavior?
had the same issue until i found this solution:
In addition to the array_values technique it is possible to use array_splice and remove an element and re-index in one step:
unset($a[1]);
Instead:
array_splice($a, 1, 1);
quoted from here: https://stackoverflow.com/a/3869219/4809658
The best way to do that is,
$json_arr = array_values($json_arr);
Although you have solved your issue at client side, I thought it would be helpful to show my solution to this issue using PHP, the idea is to construct a new array and exclude items that are not wanted, this way you will not have the indexing issue caused by unset, something like this:
$new_nodes= array();
for ($j = 0; $j < count($composition->nodes); $j++)
{
//exclude some nodes
if ($id!= $composition->nodes[$j]->id)
{
// store only the nodes that you want:
array_push($new_nodes, $composition->nodes[$j]);
}
}
// and finally, use the new modified nodes array:
$composition->nodes= $new_nodes;
Why do you need to prevent this behavior? When you convert the json to a PHP array, regardless of the JSON format is going to be an index array (have the numbers you shown) regardless.
If the numbering is incorrect use http://php.net/manual/en/function.array-values.php to fix.
Regenerated your json with this PHP script
<?php
$arr = array
(array('nome' => 'LABORGHINI GALLARDO',
'descrizione' => 'LAMBORGHINI GALLARDO ED. NERA- ANNO 2007-',
'indirizzo_pubblicato' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/LABORGHINI GALLARDO31072013-023853.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/IMG_1414 (600x448).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/index.html'),
array('nome' => 'RENAULT MEGANE',
'descrizione' => 'RENAULT MEGANE -ANNO 2006-DIESEL-CC. 1461',
'indirizzo_pubblicato' => 'autocaricateeea/RENAULT MEGANE31072013-024103/RENAULT MEGANE31072013-024103.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/RENAULT MEGANE31072013-024103/P1080949 (600x450).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/RENAULT MEGANE31072013-024103/index.html'),
array('nome' => 'FORD MONDEO',
'descrizione' => 'FORD MONDEO SINISTRATA- ANNO 2009- DIESEL- CC. 1997-',
'indirizzo_pubblicato' => 'autocaricateeea/FORD MONDEO31072013-045216/FORD MONDEO31072013-045216.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/FORD MONDEO31072013-045216/P1080971 (600x450).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/FORD MONDEO31072013-045216/index.html')
);
$arr_json = json_encode($arr);
var_dump($arr_json);
?>
Preferably the JSON may be parsed with JS so that the required car is accessed. There is no need to modify the JSON with PHP.
I searched and tried anyway to implement the behaviour that i searched in my question but i didn't find nothing. I supposed that, like you can see in this answer, unset function adds indices to the array because the JSON_encode not support arrays with hole. So, to solve my problem, i load the JSON file with a jQuery function, delete the elements with jQuery and i call a ajax function to delete the files linked at the address contained in the json file:
$.getJSON('loadauto.json', function(result) {
var y = result;
$.each(result, function(i, field){
if(field.indirizzo_paginaauto == x){
delete result[i];
}
});
$.ajax({
async: true,
cache: false,
type: 'POST',
url: 'deleteauto.php',
data: { nuovofilejson: y, indirizzo: x},
success: function(data) {
alert ("Auto cancellata definitivamente");
},
error: function(data) {
alert ("Error");
}
});
}

JSON object to PHP associative array

I am building an array in JS as such:
var slots = {};
$(".taken").each(function(item) {
var key = $(this).attr("id");
slots[key] = "<?php echo $_SESSION['alias']; ?>";
});
var json = JSON.stringify(slots);
var date = "<?php echo $_GET['date']; ?>"
$.ajax({
type: "POST",
url: "controllers/dutyupdate2.php",
data:{ array : json, date: date },
success : function(response){
console.log (response)
}//end success
});//end ajax
In my PHP script I am posting to, I need to decode it to match the following format:
array( 'D1P'=>"JohnC" , 'D6E' => "JohnC")
I get:
Array(
[D2E] => JohnC
[D6E] => JohnC
[D3BU] => JohnC
)
No matter how I decode the array, I get an indexed array with my key as the index.
Am I building the array incorrectly in the JS code or decoding incorrectly?
Thanks in advance
This is the format you want, just displayed differently. See this PHP code to verify
$a = array( 'D1P'=>"JohnC" , 'D6E' => "JohnC");
print_r($a);
this gives
Array
(
[D1P] => JohnC
[D6E] => JohnC
)
as output. So, there's no need to try or search anything different.

How to get the POST values from serializeArray in PHP?

I am trying this new method I've seen serializeArray().
//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
So I get these key value pairs, but how do I access them with PHP?
I thought I needed to do this, but it won't work:
// in PHP script
$data = json_decode($_POST['data'], true);
var_dump($data);// will return NULL?
Thanks, Richard
Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try
$data = json_decode($_POST['data'], true);
var_dump($data);
If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.
EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not JSON. Apparently, there is no Object2JSON function in jQuery so either use https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.
The OP could have actually still used serializeArray() instead of just serialize() by making the following changes:
//JS
var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array
its possible by using the serialize array and json_decode()
// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call
//PHP
$value = (json_decode(stripslashes($_REQUEST['values']), true));
the values are received as an array
each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name']
print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test#gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) )
The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:
http://www.tutorialspoint.com/jquery/ajax-serializearray.htm
I have a very similar situation to this and I believe that Ty W has the correct answer. I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php.
// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...
// PHP
echo $_POST['fieldName'];
This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output.
the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']
edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.
Maybe it will help those who are looking :)
You send data like this:
$.ajax({
url: 'url_name',
data: {
form_data: $('#form').serialize(),
},
dataType: 'json',
method: 'POST'
})
console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'
Then on the server side use parse_str( $_POST['form_data'], $res).
Then the variable $res will contain the following:
Array
(
[f_ctrType] => 5
[f_status] => 2
[f_createdAt] => '2022/02/24'
[f_participants] => 1700
)
You can use this function in php to reverse serializeArray().
<?php
function serializeToArray($data){
foreach ($data as $d) {
if( substr($d["name"], -1) == "]" ){
$d["name"] = explode("[", str_replace("]", "", $d["name"]));
switch (sizeof($d["name"])) {
case 2:
$a[$d["name"][0]][$d["name"][1]] = $d["value"];
break;
case 3:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
break;
case 4:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
break;
}
}else{
$a[$d["name"]] = $d["value"];
} // if
} // foreach
return $a;
}
?>

Categories