I have the following in myfile.php
$json_data = '{"type":"email","msg":"some text"}';
Instead of typing "email" or "some text" I want to concat the php variables $thetype and $themsg to the line before.
How can I do that? No matter what I do I get a syntax error.
I'm trying:
$json_data = '{"type":"+$thetype+","msg":"+$themsg+"}';
But as I say errors galore.
Thanks a lot
Your question is a little vague...
Are you looking for this?
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
That will set $json_data to a string like what you described:
<?php
$thetype = 'something';
$themsg = 'something else';
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
var_dump($json_data);
Would print:
string(43) "{"type":"something","msg":"something else"}"
See the PHP manual for json_encode.
You could try and build the string by hand, like this:
$json_data = '{"type":"'. addcslashes($thetype,"\"'\n").'","msg":"'. addcslashes($themsg,"\"'\n").'"}';
But, you'll generally be better off using json_encode, as it's designed for this purpose and is much less likely to produce invalid JSON.
PHP has a function to encode json.
HOWEVER you need to output it as an object to save the keys.
This is a 3D array by the way.
$data[]=array('type' => $thetype0, 'msg' => $themsg0);
$data[]=array('type' => $thetype1, 'msg' => $themsg1);
$json=json_encode((object)$data);
EDIT: This method should be used for OLDER PHP versions. It is compatible with PHP 5.3.
The json_encode() function has several changes to it that makes it so the object output isnt available in PHP 5.2.
Related
I have used JSON objects before and they work perfectly but the JSON objects that I made before have been from a result of fetched MySQL entries. Now, I am trying to make my own JSON object through an array in PHP and it shows correctly in the database but I cannot access any of the values like before.
$chatArray = array(
array(
'chatusername' => 'Troy',
'chatuserid' => '123',
'chatmessage' => 'Hello World'
),
array(
'chatusername' => 'Nick',
'chatuserid' => '124',
'chatmessage' => 'Testing'
));
$inputArray = json_encode($chatArray);
That is what I input into my database and like I said it works good. Then I call for it in a separate .php and get this
{"chat":"[{\"chatuserid\": \"123\", \"chatmessage\": \"Hello World\", \"chatusername\": \"Troy\"}, {\"chatuserid\": \"124\", \"chatmessage\": \"Testing\", \"chatusername\": \"Nick\"}]"}
It throws the "chat" out front which is the column name in my database which I am not sure why.
When I trace it I can only seem to trace it by
var messageArray:Object = JSON.parse(event.target.data);
trace(messageArray.chat);
Any time I try to reference say messageArray.chat.chatusername it returns an error.
I'm sorry I know it is probably a simple solution but I have been searching and working at it for a few hours now.
Any help is much appreciated! Thank you!
From the PHP code that generates your JSON output:
$stmt = $conn->prepare("SELECT chat FROM markerinfo WHERE markerid='$chatid'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Keep in mind that the chat column in your database contains a JSON-string.
This code is not decoding the JSON-string in your database, so $result will be an array containing a JSON-string as well:
$result = [
'chat' => '[{"chatusername":"Troy","chatuserid":"123","chatmessage":"Hello World"},{"chatusername":"Nick","chatuserid":"124","chatmessage":"Testing"}]'
];
By passing that array through json_encode(), you're double-encoding your JSON-string.
For your purposes, you can probably get away with:
echo $result['chat'];
But, if you want the chat column name to be included in your output, you will have to decode the stored JSON first:
$result['chat'] = json_decode($result['chat']);
echo json_encode($result);
Probably this is related to the php side when it encodes your array, it will escape it with slashes, and this confuses the JSON parsing in your JS side. Try to add the JSON_UNESCAPED_SLASHES option to your json_encode function like this:
$inputArray = json_encode($chatArray, JSON_UNESCAPED_SLASHES);
Check the json_encode function documentation for more details:
http://php.net/manual/en/function.json-encode.php
I wanted to try something out with an API from a company. I wanted to put their data into my database. But I've run into a problem. The API has one JSON object called "venue.country". But I can't use dots in my array for some reason?
Here is the code:
foreach ($data[1]['hits']['hits'] as $row) {
$statement->execute(array(
"name" => $row['fields']['name'][0],
"date" => $row['fields']['start'][0],
"lang_long" => "test",
It is this one! -> "country" => $row['fields']['venue.country'][0],
"genres" => $row['fields']['genres'][0],
"desc" => $row['fields']['description'][0],
"logo" => $row['fields']['logo'][0],
"header_pic" => $row['fields']['header'][0]
));
}
\everything else works in the PHP
And here is a piece of the JSON:
venue.country: [
"Nederland"
],
How can I get this to work? Can I use the "explode" method?
This is the full JSON:
https://hugo.events/genre/pop/next/200/120
Thanks.
EDIT:
Even with the answer #Prototype Chain gave it is giving me this error: Notice: Undefined index: venue in /home/ubuntu/workspace/pop.php on line 18
This code works just fine given your example JSON data:
$string = <<<EOT
{INSERT YOUR JSON STRING HERE}
EOT;
$json = json_decode( $string, true );
echo $json[1]['hits']['hits'][0]['fields']['venue.location'][0] . "\n";
echo $json[1]['hits']['hits'][0]['fields']['venue.location'][1] . "\n";
The code works fine. After debugging I found that, there is no key/index venue.country for the array elements $data[1]['hits']['hits'][50] and $data[1]['hits']['hits'][51]. Since there is no index, its throwing notice.
You can add #before the variable to suppress the notice or check the condition if the index exixts.
"country" => #$row['fields']['venue.country'][0],
"country" => isset($row['fields']['venue.country']) ? $row['fields']['venue.country'][0] : '',
// run this code for testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$jsondata = file_get_contents('https://hugo.events/genre/pop/next/200/100');
$data = json_decode($jsondata, true);
foreach ($data[1]['hits']['hits'] as $row) {
// echo $row['fields']['name'][0].'=>'.#$row['fields']['venue.country'][0].'<br/>';
$array[]= array(
"name" => $row['fields']['name'][0],
"country" => isset($row['fields']['venue.country']) ? $row['fields']['venue.country'][0] : ''
);
}
echo "<pre>";
print_r($array);
It's a little hard to debug without seeing the entire contents of the JSON data, however, in the past when I've hard trouble parsing JSON or XML data from a source that formatted it strangely, I found it useful to perform a pre-process str_replace() on the data before I parsed it.
So something like this might work for you:
$input = some_function_to_get_string_data_from_api();
$input = str_replace( "venue.country", "venuecountry", $input );
$json = json_encode( $input );
It's not an elegant solution, and it falls apart quickly if you're dealing with lots and lots of fields that need modifying, but if you're only dealing with a single field or two that are giving you trouble, it can be a quick and dirty patch.
Hope this will do the trick..
$row['fields']['venue']['country'][0]
After googling, implementing code upon code, I still cannot get ANYTHING to display. Nothing. Not one thing.
I have a URL spitting out JSON:
{"videos":[{"video":{"name":"Sanyo Zio","youtube":"FxxLDr--R5A","post_date":"2010-10-08 01:00:00",...
Here's the code I'm using to access the page:
$url = file_get_contents("http://[website]/json/test.json");
$arr = json_decode($url,true);
Now here's a short list of what I've tried to access ANY data from the page:
1:
print_r($arr);
2:
foreach($arr['videos']['video'] as $item) {
echo "Name: ". $item[0] ."<br>";
}
3:
$obj = $arr[0];
echo $obj;
4:
foreach($arr as $a){
echo "Name: ".$a['videos']['video']['name']."<br />";
}
Clearly I'm missing something, but I just haven't been able to figure out what I'm doing wrong! Is my encoding not correct? Here's how I'm encoding the JSON to begin with:
$arr = array('videos' => array());
foreach($vid as $items){
$arr['videos'][] = array('video' => array(
'name' => $items['videoName'], 'youtube' => $items['youtubeID'], 'post_date' => $items['productionTimestamp'], 'description' => $items['videoDesc'], 'link' => $single_linker_values['deeplink'], 'image' => $image));
}
echo json_encode($arr);
Any ideas/suggestions?
Update - Apparently the server is locked down, but being inhouse I don't notice :) Obviously the webpage does! Thanks for the help!
From PHP Manual
NULL is returned if the json cannot be decoded or if the encoded data
is deeper than the recursion limit
Since you are not specifying a recursion limit, chances are that either your JSON is invalid or nothing is being retrieved from your URL.
Three things to try:
determine if there was a json_decode error
print_r(json_last_error()); // call after json_decode
check that data is being returned
print_r($url);
see if data will decode as an object
$obj = json_decode($url);
print_r($obj);
I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));
EDIT
Solved it. It was before the ajax call and, hence, this code. Thank you all for the answers.
I can't find anybody with this problem. I have a AJAX call to a PHP script that returns a JSON response.
I fetch the values from a database into an array:
while($row = mysql_fetch_array($ret)){
$temp = array(
'id' => $row['id_reserva'],
'start' => $row['data_inicio'],
'end' => $row['data_fim'],
'title' => $row['descricao']
);
$js[] = $temp;
}
Headers:
header('Content-type: application/json');
And echo:
echo json_encode($js);
There is no return whatsoever, just a null string.
What is really bugging me is that if instead of this I create a json string with the previous result directly in the code:
$temp = '[{"id":"3914", "start": "2011-08-25 09:00:00",
"end":"2011-08-25 18:00:00", "title":"asdasdasd"},
{"id":"3915", "start": "2011-08-25 09:00:00",
"end":"2011-08-25 18:00:00", "title":"asdasdasd"}]';
echo $temp;
It works.
Tried changing the file codification, comparing the strings, checking for some problem with chars, and nothing.
Anybody?
Cheers
you have to encode it. try
echo json_encode($js);
You need to json encode array:
echo json_encode($js);
You're not outputting as JSON?
echo json_encode($js);
With your method, when jQuery gets the response and cannot parse the JSON it will return the empty string as you have experienced.
Process of elimination..
can you print_r ($js) and get output?
Take out the header(); statement, does anything appear?
Do you have error_reporting and display_errors turned on?
You don't seem to initializing 'js' ($js = array()). If you get the literal string 'null' back, this could simply imply that your query is not returning any results.
I could add this statement to almost every long-winded PHP requestion on stack overflow:
Go through your code step by step and echo what you expect the contents of variables to be at that point. Then you'll slowly isolate exactly where your issue is; there's nothing wrong with your code as-is.
Are you not making a multi-dimentional array with $js[] = $temp; and then encoding that? Try just doing json_encode($temp);