Below is a sample json code that I want to access...This json is actually coming from an API. Whenever I copy and paste the entire json in json lint..It says valid json..
foreach ($movies as $movie) {
echo "theaters ".var_dump($movie->release_dates->theater)";
}
//Im actually trying to access a nested json in php... Something like
{
"movies":[{
"tile":"Cowboys";
"release_dates":{"theater":"2013-11-29"},
so on....
Whenever I try to write the above it gives me an error Object of stdclass cannot be converted to string ....Or if I write
$x = json_decode(var_dump($movie->release_dates->theater), true)";
echo "theaters "$x[0];
It gives an output like string[10]:2013-11-25 string[10]:2013-11-30....So on..What is the error....
$data = json_decode($movies, true);
foreach ($data as $movie) {
echo "theaters ".implode(', ', $movie->release_dates->theater)";
}
Related
If you open the URL, you'll see that it's a very long string of sub objects. I want to extract the values for the 70 position. So far I've been able to extract the first tree without a problem ... But if you go deeper then I don’t get any feedback at all. Please check the code below and tell me, what am I doing wrong?
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port); // decode the JSON feed
echo $data[69]->port_name.'<br>';
echo $data[69]->port_status.'<br>';
echo $data[69]->passenger_vehicle_lanes->maximum_lanes.'<br>';
echo $data[69]->passenger_vehicle_lanes->standard_lanes->lanes_open.'<br>';
The following is working for me:
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port, true); // decode the JSON feed
echo "There are ".count($data)."Ports".PHP_EOL;
$found=false;
foreach ($data as $key => $value) {
//EDIT AFTER COMMENT**
if($value['port_number']==250401){
echo $value['port_name'].' '.$value['crossing_name'].PHP_EOL;
$found=true;
break;
}
}
if(!$found) echo "couldn't find port #";
can you try to change json_decode($port, true); (true will change object to array and it will be better to access it) like this and access it like in array echo $data[69]['passenger_vehicle_lanes']['maximum_lanes'].'<br>';
My json data looks like this :
{
"amount":550,
"items":[
{"item_id":12334, "price": 504},
{"item_id":12335, "price":206}
]
}
I want to know how to parse this data in order to fetch each information in separate variable.
In PHP you can use json_decode($myJsonString), while in Android you might look for a third party library, GSON is a good one though
$data = json_decode($json);
foreach($data->items as $item) {
echo $item->item_id . ' ' . $item->price;
}
In PHP use json_decode
In Java use org.json.simple
Create local variable suppose $response;
store your output in $response;
You can fetch price by following code.
foreach ($response->items as $item){
echo $item->price;
echo "<br>";
}
I have a problem with unserializing serialized data.
The data is serialized and saved in the database.
This data contains a uploaded .csv url that I want to give back to fgetcsv.
fgetcsv expects a array and now a string is given, so I need to unserialize the data but this gives me errors.
I found this online http://davidwalsh.name/php-serialize-unserialize-issues but this doesn't seem to work. So I hope somebody can tell me where I go wrong:
Here is the error:
Notice: unserialize() [function.unserialize]: Error at offset 0 of 1 bytes in /xxx/public_html/multi-csv-upload.php on line 163
I found that this means that there are certain characters in the serialized data that makes the file corrupt after unserialization (",',:,;)
Line 163:
jj_readcsv(unserialize ($value[0]),true);` // this reads the url of the uploaded csv and tries to open it.
Here is the code that makes the data serialized:
update_post_meta($post_id, 'mcu_csv', serialize($mcu_csv));
This is WordPress
Here is the output of:
echo '<pre>';
print_r(unserialize($value));
echo '</pre>';
Array
(
[0] => http://www.domain.country/xxx/uploads/2014/09/test5.csv
)
The way I see it there shouldn't be anything wrong here.
Anybody some idea's how I can unserialize this so I can use it?
Here is what I did sofar...
public function render_meta_box_content($post)
{
// Add an nonce field so we can check for it later.
wp_nonce_field('mcu_inner_custom_box', 'mcu_inner_custom_box_nonce');
// Use get_post_meta to retrieve an existing value from the database.
$value = get_post_meta($post->ID, 'mcu_images', true);
echo '<pre>';
print_r(unserialize($value));
echo '</pre>';
ob_start();
jj_readcsv(unserialize ($value[0]),true);
$link = ob_get_contents();
ob_end_clean();
$editor_id = 'my_uploaded_csv';
wp_editor( $link, $editor_id );
$metabox_content = '<div id="mcu_images"></div><input type="button" onClick="addRow()" value="Voeg CSV toe" class="button" />';
echo $metabox_content;
$images = unserialize($value);
$script = "<script>
itemsCount= 0;";
if (!empty($images))
{
foreach ($images as $image)
{
$script.="addRow('{$image}');";
}
}
$script .="</script>";
echo $script;
}
function enqueue_scripts($hook)
{
if ('post.php' != $hook && 'post-edit.php' != $hook && 'post-new.php' != $hook)
return;
wp_enqueue_script('mcu_script', plugin_dir_url(__FILE__) . 'mcu_script.js', array('jquery'));
}
You are attempting to access the first element of the serialized string:
jj_readcsv(unserialize ($value[0]),true);
As strings are essentially arrays of chars, you are trying to unserialize the 1st char of the serialized string.
You need to unserialize 1st then access the array element:
//php 5.4+
jj_readcsv(unserialize ($value)[0],true);
//php < 5.4
$unserialized = unserialize ($value);
jj_readcsv($unserialized[0],true);
Alternatively, if there is only ever one element, dont store an array in the 1st place, just save the url string, which doesnt need to be serialized:
//save
update_post_meta($post_id, 'mcu_csv', $mcu_csv[0]);
//access
jj_readcsv($value, true);
I am attempting to get a JSON feed output from attributes of an XML feed. I can get the data out of the XML, however, I am unable to get it to format correctly. The error seems to be with the json_encode not adding the curly braces to the outputted date. This is the code I have so far:
<?php
$url = 'http://cloud.tfl.gov.uk/TrackerNet/LineStatus';
if(!$xml = simplexml_load_file($url))
{
die("No xml for you");
}
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
echo $line->Line['Name'];
echo $line->Status['Description'];
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
?>
The problem is that you're not storing the name and description into the array.
Try this:
foreach ($xml->LineStatus as $line)
{
$linestatus[] = array('name' => $line->Line['Name']);
$linestatus[] = array('description' => $line->Line['Description']);
}
Demo!
The echos are screwing everything up. I think you intend to append to linestatus which remains empty per your code.
$linestatus[] = array(
"name" => $line->Line['Name'],
"description" => $line->Status['Description']
);
You also need to use echo instead of print_r to actually emit the JSON.
You are declaring $linestatus as an array, then never put anything in it before finally encoding it and trying to output it. Of course it won't work as expected! Instead, you should be populating it with values:
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
$linestatus[] = $line->Line;
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
I have a PHP script that's being called through jQuery AJAX. I want the PHP script to return the data in JSON format to the javascript. Here's the pseudo code in the PHP script:
$json = "{";
foreach($result as $addr)
{
foreach($addr as $line)
{
$json .= $line . "\n";
}
$json .= "\n\n";
}
$json .= "}";
Basically, I need the results of the two for loops to be inserted in $json.
Php has an inbuilt JSON Serialising function.
json_encode
json_encode
Please use that if you can and don't suffer Not Invented Here syndrome.
Here are a couple of things missing in the previous answers:
Set header in your PHP:
header('Content-type: application/json');
echo json_encode($array);
json_encode() can return a JavaScript array instead of JavaScript object, see:
Returning JSON from a PHP Script
This could be important to know in some cases as arrays and objects are not the same.
There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
If you don't, here's the PECL library you can install.
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
Usually you would be interested in also having some structure to your data in the receiving end:
json_encode($result)
This will preserve the array keys as well.
Do remember that json_encode only works on utf8 -encoded data.
You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
$msg="You Enter Wrong Username OR Password";
$responso=json_encode($msg);
echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";