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]
Related
I've an array titled $request as follows :
Array
(
[invite_emails] => suka#gmail.com, swat#gmail.com
[page_id] => 322
[ws_url] => http://app.knockknot.com/api/group/sendInvitation
)
After using json_encode($request) I got following output:
{
"invite_emails": "suka#gmail.com, swat#gmail.com",
"page_id": "322",
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
But actually I want the JSON object as follows :
{
"page_id": 322,
"invite_emails": [
"suka#gmail.com",
"swat#gmail.com"
],
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
How should I manipulate the array in PHP in order to get the above desired JSON object?
Please someone help me.
Split the list of emails using the comma:
$array["invite_emails"] = preg_split("#\s*,\s*#", $array["invite_emails"]);
I personally prefer using callback functions for readability and possibilities. To your purpose, array_walk should fit:
<?php
// reproducing array
$request = array(
"invite_emails" => "suka#gmail.com, swat#gmail.com",
"page_id" => 322,
"ws_url" => "http://app.knockknot.com/api/group/sendInvitation"
);
// callback finds a comma-separated string and explodes it...
array_walk($request, function (&$v,$k) {if ($k == 'invite_emails') $v = explode(", ", $v);});
// ... and then encode it to JSON
json_encode($request);
// testing
print_r($request);
OUTPUT:
{
"invite_emails":[
"suka#gmail.com",
"swat#gmail.com"
],
"page_id":322,
"ws_url":"http://app.knockknot.com/api/group/sendInvitation"
}
You are free to change the field if your needs changes, and even suppress it to be used with any field of the array.
Use PHP explode for example:
$array['invite_emails'] = explode(',',$array['invite_emails']);
To avoid spaces use preg_split (source):
$array['invite_emails'] = preg_split("/[\s,]+/", $array['invite_emails']);
This entry:
[invite_emails] => suka#gmail.com, swat#gmail.com
should be an array (currently, it is a string) in PHP, then in JSON it will look like you want it.
I am trying to fix a bit of code and display an image that is set with a custom metabox. I have found the saved data in wp_postmeta and it looks like the data is saved as a string but I can see an obvious key value pair.
When I use the following code...
$imgVar = get_post_meta($post->ID, 'attachments', true);
$testing4 = $imgVar;
var_dump($testing4);
...I get the following output...
string(101) "{"my_item":[{"id":"653","fields":{"title":"mytitle","caption":"test this out"}}]}"
... this looks like it is telling me that the output is a string with 101 characters but I see key values and an array.
what I would like to have output is, or what it seems it should be...
array[0](
"my_item" => array(
"id" => "653",
"fields" => array(
"title" =>"mytitle",
"caption" => "test this out"
),
)
),
can someone explain what is being output for this newb :), and if it is possible to turn what is being output into a regular array. Or if I can access the key value "id => 653" without switching the output.
Thanks.
The output-string is probably serialized (easier for Wordpress to store data more efficient).
Try:
<?php maybe_unserialize( $original ) ?>
If you want to know more about this look at: http://codex.wordpress.org/Function_Reference/maybe_unserialize
$var = json_decode($testing4);
Format output with <pre> tags
echo '<pre>' . var_dump($testing4) . '</pre>';
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))));
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.