Parsing javascript into php Object - javascript

I have the following javascript file
sample.js
var sampleName = "a nice name";
var sampleObject = {name: 'sample', type: 'text'}
I want somehow to parse this file with php and generate the equivalent values, objects into php in order to use them there.
So for example after pasring the js file I would like somehow to be able to access the values with something like that
echo $javascriptParser->sampleObject->name; //should return sample
echo $javascriptParser->sampleName; //should return a nice name
So far I was not able to find anything like that?
Does anyone know if something like that exists out there?
Thanks in advance.

pass your string and do some replacements....
$json = "{name: 'sample', type: 'text'}";
$search = array(":",", ","{","'");
$replace = array("\":",",\"","{\"","\"");
$json = str_replace($search, $replace, $json);
$obj = json_decode($json);
echo $obj->name;
you can write it to a function like:
function convert($str)
{
$search = array(":",", ","{","'");
$replace = array("\":",",\"","{\"","\"");
$str = str_replace($search, $replace, $str);
$obj = json_decode($str);
return $obj;
}
$obj = convert("{name: 'sample', type: 'text'}");
echo $obj->name;
i guess you should do some about the whitespaces... i just replaced it with it... but better you use something like trim or instead use regexp to replace. so there can be no errors with whitespaces

Related

How do I get values from a PHP array to a Javascript Array?

So I am currently doing some coding for the website of someone of my outer family and I had to create a bar chart and now I need to fill it with data from their SQL-Database. First I just echo'd the array like this:
PHP:
<?php
$exampleArray = ["212", "33", "7"]
?>
and JS:
<script> var jExampleArray = <? echo json_encode($exampleArray);?>; </script>
And then I used jExampleArray in my bar chart code. Now I was very happy but the they say that it needs to be more secure (it involves their company) and I have to find a way to make sure nobody can just see the data while looking through the code on the page. I thought about using Ajax and what not but it just didn't work for me. I got it to alert me the array, but was not able to fill a Javascript array with it.
I never did stuff with JS, PHP oder SQL before and only learned Java in school so I am pretty clueless and most of the stuff I did was with help of the Internet. Luckily I managed to at least understand the code I wrote/copied.
Edit: [] for a JS array not {}
Your syntax for creating the PHP array is incorrect.
Use the function json_encode to transform PHP arrays into Javascript arrays and objects.
<?php
$arr = ['hello', 'world', 'foo', 'bar'];
$obj = ['hello' => 'world', 'foo' => 'bar'];
echo 'var Array = ' . json_encode($arr) . PHP_EOL .
'var Obj = ' . json_encode($obj, JSON_FORCE_OBJECT) . PHP_EOL;
Will result in the following:
var Array = ["hello","world","foo","bar"]
var Obj = {"hello":"world","foo":"bar"}
Some pseudo code to show how you might accomplish the stated goal
$data=array();
while( $rs=$db->fetch() ){
$data[]=array(
'field_1' => $rs->field_1,
'field_2' => $rs->field_2,
'field_3' => $rs->field_3
);
}
$json=json_encode( $data );
<script>
<?php
echo "var jExampleArray={$json};";
?>
/* rest of barchart code */
</script>
If the PHP array is available at page load use:
<?php
$phpArray = array('data1' => 2, 'data2' => 3);
?>
<script>var arr = <?php echo json_encode($phpArray); ?>;</script>
To retrieve PHP array in JS after page load using ajax:
var arr = JSON.parse(responseArray);

Json decode using content of array

I'm training myself (JSON and PHP) and I have a problem
I have Json decode look like this :
"playerstats": {
"steamID": "75068112",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 2314497
},
{
"name": "total_deaths",
"value": 1811387
},
And to parse into php i do :
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo $json['playerstats']['stats'][1]['name']
And it works but the problem is when i change the id to get stats, the order of the array isn't the same :/
So i can't use [2] or any else number to get data.
I post here to know how could'i get stats using the attribute name of each array ('total_kills' for example) instead of [1]..[2]..
thanks for all your support
Use foreach and use if condition to check the name is 'total_kills' is true then store it into new array like this .
<?php
$json = json_decode($content, true);
$new_array =array();
$i=0;
foreach($json['playerstats']['stats'] as $row )
{
if($row['name']=='total_kills')
{
$new_array[]=array($row['name']=>$row['value']);
}
if($i<10)
{
break;
}
$i++
}
print_r($new_array);
?>
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['playerstats']['stats'] as $row )
{
echo $row['name'];
echo $row['value'];
}
What you're looking for is a way to loop over the array. In PHP you can do the following;
$url = 'myurl';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json["playerstats"]["stats"] as $stat){
if($stat["name"] == "total_kills"){
echo "total kills: ".$stat["value"];
}
elseif($stat["name"] == "total_deaths"){
// ...
}
// etc... continue to select all parameters you would like
}
This will allow you to get the value for each stat with name using the if else statement.
Another way to do something with all objects in an array is to use the array_map() function, which takes another function as one of its arguments. Using this whenever you can will force you to adhere to good programming practices, because the passed in function cannot modify values outside of the array and arguments passed in via use.

Adding a new associative element to a JSON object

i have the problem to add elements to an json array.
The structure i want is that:
[{"method":"edit","type":"1", "template":"3", "meta":{"title":"Tools", "descirption":"Tools"}}]
The problem is that i add all these parameters dynamically.
So lets say i have for the start:
[{"method":"edit","type":"1", "template":"3"}]
How can i add the whole "meta" array and please do not be with push(), because than i will have another structure when i print it.
When i use
$json = json_decode($json, true);
I want to have:
array(
method' => edit,
'type' => 1,
'template' => 3,
'meta' => array('title' => '')
);
Thanks in advice !
So I'm going to assume you have the JSON to start with. So let's decode to PHP (as you noted correctly)
$json = json_decode($json, true);
So now we should have $json['method'], etc. Now let's define $meta
$meta = array('title' => '');
And add this to $json
$json['meta'] = $meta;
echo json_encode($json);
When your current JSON decodes in PHP using json_decode, it will decode into an array with one element, or array[0]. Therefore in order to access or any object you need to first point to that 0 index. Do it this way:
$json = '[{"method":"edit","type":"1", "template":"3"}]';
$arr = json_decode($json);
$arr[0]->meta = array('title' => '');
$json = json_encode($arr);
var_dump($json);
//Result:
// string '[{"method":"edit","type":"1","template":"3","meta":{"title":""}}]' (length=65)

JSON in Php not working

I have a problem and do not know what the problem is. I have a javascript variable in my html. which is:
var people = '{"names": ["Matthew", "Lucas", "Todd", "Roxie", "Kyle", "Ken", "Gideon"], "surnames": ["Patel", "Lee", "Ingram", "Richter", "Katayanagi", "Katayanagi", "Graves"]}';
I parse the variable on one function in my script and use it. Everything works fine.
var mydata = JSON.parse(people);
But then I need to send the data to a php file, I send it by wrtting the data to a hidden input.
var strObject = JSON.stringify(mydata);
var replaced = strObject.replace(/\//g, '');
oFormObject = document.forms['theForm'];
oFormObject.elements["jsonData"].value = replaced;
After which I try to encode it in my decode.php using:
$obj = $_POST['jsonData'];
json_decode($obj);
$s = stripslashes($obj);
var_dump($s);
But when I do a var_dump($s) I get this output:
string(147) "{"names":["Matthew","Lucas","Todd","Roxie","Kyle","Ken","Gideon"],"surnames":["Patel","Lee","Ingram","Richter","Katayanagi","Katayanagi","Graves"]}"
Thus, I cannot output the contents in $s.Any suggestions.Please let me know if you need more information. BTW, its a homework assignment and I am stuck with the last section.
try saving json_decode($obj) to a variable and var_dump that
something like
var $temp = json_decode($obj);
var_dump($temp);
the answer already is in the comments, but since this is the answer, i just post it as an answer.
you need to work with the return value from json_decode(). json_decode($obj) doesn't change the content of the variable $obj by itself:
$obj = $_POST['jsonData'];
$obj = json_decode($obj);
$obj = stripslashes($obj);
var_dump($obj);
If you are looking for name surname pairs from json , you can try this
$a = '{"names": ["Matthew", "Lucas", "Todd", "Roxie", "Kyle", "Ken", "Gideon"], "surnames": ["Patel", "Lee", "Ingram", "Richter", "Katayanagi", "Katayanagi", "Graves"]}';
$b = json_decode($a);
$c = $b->names;
$d = $b->surnames;
for ($i = 0;$i< count($b->names); $i++){
echo $c[$i]." ". $d[$i] ."<br>";
}

How can a JSON model be handled in PHP?

I have a JSON model in my view which I am passing to a PHP script. The model looks like this:
{
FirstName: "Paul",
SurName: "Krampe"
}
I send it to the backend using JSON.stringify(). In PHP, this object arrives as:
{\\\"FirstName\\\":\\\"Paul\\\",\\\"SurName\\\":\\\"Krampe\\\"}
How can I read the members now and assign them to variables?
I tried
$firstName = $newUserObject["FirstName"];
and
$firstName = $newUserObject->FirstName;
but they are both null.
php's function json_decode() decodes string JSON argument into an object and returns that object .
there's also json_encode() function that does the opposite: encodes php object, or array, etc. into JSON string.
Use the built in json_decode function
$array = json_decode($json);
Then access the data with
$array['FirstName'];
Additionnaly you would have to remove the extra slashes in your JSON input by calling before the json_decode function the following format function:
$json = str_replace('\\\\\\', '', $json);
You can do something like this
<?php
$jsonurl = "yourfile.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo $trend->name;
}

Categories