I have a file that contains the following HL7 Information :
{
MESSAGE_HEADER: {
SENDING_APPLICATION: 'IQCARE',
SENDING_FACILITY: '10829',
RECEIVING_APPLICATION: 'IL',
RECEIVING_FACILITY: '10829',
MESSAGE_DATETIME: '20170713110000',
SECURITY: '',
MESSAGE_TYPE: 'ADT^A04',
PROCESSING_ID: 'P'
},
PATIENT_IDENTIFICATION: {
EXTERNAL_PATIENT_ID: {
ID: '110ec58a-a0f2-4ac4-8393-c866d813b8d1',
IDENTIFIER_TYPE: 'GODS_NUMBER',
ASSIGNING_AUTHORITY: 'MPI'
}}}
I want to convert this message to a json object and I did the following :
// copy file content into a string var
$json_file = file_get_contents("" . getcwd() . "\integration_layer\ADT^A04 - Patient Registration.json");
echo gettype($json_file);
// convert the string to a json object
$jfo = json_decode($json_file);
// read the title value
$title = $jfo->MESSAGE_HEADER->SENDING_APPLICATION;
// copy the posts array to a php var
$posts = $jfo->PATIENT_IDENTIFICATION->EXTERNAL_PATIENT_ID;
// listing posts
foreach ($posts as $post) {
echo $post->ID;
}
But I get the following error :
Severity: Notice
Message: Trying to get property of non-object
When I user the getype function of PHP on the $json_file , it is a string file.
How can I convert the message to an object for my own system consumption ?
Please validate your JSON code.
JSON rules
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects - Your file contains no parent object
Square brackets hold arrays
A name/value pair consists of a field name (in double quotes). -
Your name fields are not in double quotes
Valid JSON code:
{
"MESSAGE_HEADER": {
"SENDING_APPLICATION": "IQCARE",
"SENDING_FACILITY": 10829,
"RECEIVING_APPLICATION": "IL",
"RECEIVING_FACILITY": 10829,
"MESSAGE_DATETIME": "20170713110000",
"SECURITY": "",
"MESSAGE_TYPE": "ADT^A04",
"PROCESSING_ID": "P"
},
"PATIENT_IDENTIFICATION": {
"EXTERNAL_PATIENT_ID": {
"ID": "110ec58a-a0f2-4ac4-8393-c866d813b8d1",
"IDENTIFIER_TYPE": "GODS_NUMBER",
"ASSIGNING_AUTHORITY": "MPI"
}
}
}
Working PHP example with valid JSON code:
<?php
$json = '
{
"MESSAGE_HEADER": {
"SENDING_APPLICATION": "IQCARE",
"SENDING_FACILITY": 10829,
"RECEIVING_APPLICATION": "IL",
"RECEIVING_FACILITY": 10829,
"MESSAGE_DATETIME": "20170713110000",
"SECURITY": "",
"MESSAGE_TYPE": "ADT^A04",
"PROCESSING_ID": "P"
},
"PATIENT_IDENTIFICATION": {
"EXTERNAL_PATIENT_ID": {
"ID": "110ec58a-a0f2-4ac4-8393-c866d813b8d1",
"IDENTIFIER_TYPE": "GODS_NUMBER",
"ASSIGNING_AUTHORITY": "MPI"
}
}
}
';
$object = json_decode($json);
echo $object->MESSAGE_HEADER->SENDING_APPLICATION;
?>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm working with a charity who need their own specific CMS to post blogs. I have set up QuillJS which works well and output JSON.
How do I convert JSON data back to HTML with the relevant tags? I need the HTML tags to be shown too such as '<p>Hello</p>'. I can get the JSON data via php mysql but don't know how to show the tags.
For example how to I convert the following
JSON
{
"time" : 1589493865899,
"blocks" : [
{
"type" : "header",
"data" : {
"text" : "Editor.js",
"level" : 2
}
},
{
"type" : "paragraph",
"data" : {
"text" : "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text."
}
}
],
"version" : "2.17.0"
}
To
HTML
<html>
<h2>EditorJS</h2>
<p>Hey. Meet the new Editor. On this page you can see it in action — try to edit this text.</p>
</html>
Many thanks in advance for any help!
Here's a complete solution. Each step is mentioned in the comments:
<?php
$jsonData = '{
"time" : 1589493865899,
"blocks" : [
{
"type" : "header",
"data" : {
"text" : "Editor.js",
"level" : 2
}
},
{
"type" : "paragraph",
"data" : {
"text" : "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text."
}
}
],
"version" : "2.17.0"
}';
//decode the JSON
$data = json_decode($jsonData);
//loop through the blocks
foreach ($data->blocks as $block)
{
$start = "";
$end = "";
//detect the element type and set the HTML tag string
switch ($block->type)
{
case "header":
$start = "<h2>";
$end = "</h2>";
break;
case "paragraph":
$start = "<p>";
$end = "</p>";
break;
}
//output the final HTML for that block
echo $start.$block->data->text.$end;
}
Demo: http://sandbox.onlinephpfunctions.com/code/ab862de1113d8744bc2d9463f7a7df2496491110
So you need to first decode the JSON so php can use it as an array and loop through foreach to display.
$someJSON = '{
"time" : 1589493865899,
"blocks" : [
{
"type" : "header",
"data" : {
"text" : "Editor.js",
"level" : 2
}
},
{
"type" : "paragraph",
"data" : {
"text" : "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text."
}
}
],
"version" : "2.17.0"
}';
Now we decode and display
$someData = json_decode($someJSON, true);
//--> Create an empty variable to hold the display text...
$output = null;
//--> Run foreach loop, we can see the associative keys in the array, this gives
//--> us everything we need to pull the data out and display it properly...
//--> loop through the converted arrays first child 'blocks' and get the values
foreach ($someData['blocks'] as $value) {
//--> If the 'type' === 'header' wrap value -> ['data'] -> ['text'] in <h2> tag
if($value['type'] === "header"){
$output .= '<h2>'.$value['data']['text'].'</h2>';
}
//--> If the 'type' === 'paragraph' wrap value -> ['data'] -> ['text'] in <p> tag
if($value['type'] === "paragraph"){
$output .= '<p>'.$value['data']['text'].'</p>';
}
}
In your HTML output the variable within php tags to display the concatenated HTML held within $output
<html>
<div id="my_id">
<span class="my_class">
<?=$output?> or <?php echo $output; ?>
</span>
</div>
</html>
http://sandbox.onlinephpfunctions.com/code/e8fdb5b84af5346d640e92e6788e5c2836b9ad07
I have a simple JSON and want to read in PHP. I am certainly missing something in array, can anybody point out my mistake. Its been considerable time I am playing with this simple thing.
Here is the JSON & php :
$string='[
{
"phone":"+91009999000",
"name":"abcd",
"typeid":1
}
{
"phone":"+91009999222",
"name":"efg",
"typeid":2
}
{
"phone":"+91009999444",
"name":"hijhl",
"typeid":1
}
]';
$json_a = json_decode($string,true);
$phone = $json_a[0]['phone'];
$full_name=$json_a[0]['courseid'];
echo "phone = " . $phone;
echo "<br>fullname = " . $full_name;
You are missing commas near curly braces.
It should be like this:
$string='[
{
"phone":"+91009999000",
"name":"abcd",
"typeid":1
},
{
"phone":"+91009999222",
"name":"efg",
"typeid":2
},
{
"phone":"+91009999444",
"name":"hijhl",
"typeid":1
}
]';
I had been following this guide to create an app using two different APIs but the guide is old and so one of the APIs does not work like it did in the guide. I am trying to grab coordinates from google geocoding API and stick them into Places for Web. I am new to PHP, so I was following the guide's example to traverse a JSON object but have been stuck all night trying to get it to work.
Here is the JSON object from the place search API
{
"html_attributions":[ ],
"results":[
{
"geometry":{ },
"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id":"d4b0fb0f7bf5b2ea7df896a0c120a68efae039cf",
"name":"Guadalajara Mexican Grill & Cantina",
"opening_hours":{ },
"photos":[
{
"height":2952,
"html_attributions":[ ],
"photo_reference":"CmRaAAAAfO4JKUaO8vCFM2dcu5LMu4mA4_HXQGJ1FyAnyJUre_kD6VOWiQj7tBEECx4AAct5AORIKipSYWg-Zprjlf8o-SFd7mBRGMXMVMwodFZ5KMLwPYPUhBnTTehGPkb9275pEhCkAqMwfmK29vYenk1wdwFvGhSIHR8ch6FONc99tGn4rVnesbuteg",
"width":5248
}
],
"place_id":"ChIJ27es4SWa3IARcvjmt3xL2Aw",
"price_level":2,
"rating":4.4,
"reference":"CmRRAAAA7Rx-l7juDX-1or5dfpK6qFcZ0trZ9cUNEUtKP2ziqHb2MhOE6egs-msJ2OdFKEuHhuNe-3Yk6yxUYwxCBqhDT3ci8pYZI4xYhPGyyDgDenbEU_8k84JiEtCGvj4bdIR0EhDR2Pqte5_kDUcCC9PJFVknGhQomvD4d7NBIhCFxI4i2iEc0w9UiA",
"scope":"GOOGLE",
"types":[ ],
"vicinity":"105 North Main Street, Lake Elsinore"
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"status":"OK"
}
I am trying to grab all the photo references into an array maybe?, and then plug them into google's Place Photos API. Here is my attempt at that:
UPDATE
<?php
if(!empty($_GET["location"])){
//$API_key = "";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($_GET['location']) .
'&key=';
$maps_json = file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
'location=$lat,$lng' .
'&radius=1500' .
'&rankby=distance' .
'&key=';
$places_json = file_get_contents($places_url);
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array as $item) {
var_dump($places_array );
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>What is Here?</title>
</head>
<body>
<h1>Type in a location</h1>
<p>This program will display pictures of places to go in that area</p>
<form action ="">
<input type ="text" name ="location"/>
<button type ="submit">Go!</button>
</form>
<br/>
<?php
echo "$lat $lng";
?>
Just can't seem to get the foreach loop to do anything
the invalid request means wrong url or bad parameters
if $lat and $lng are variables then the interpolation wont work with single quotes try using double quotes like this
"location=$lat,$lng"
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key=mykey';
you should remove radius or distance you cant get both its on the docs
https://developers.google.com/places/web-service/search?hl=en-419
here is my modified code that works on localhost please notice the $contextOptions you should not copy this on your code this is a workaround to make file_get_contents work on my machine
after that the foreach should be easy since is only an array look at the code
$thelocation = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
$thekey = "someapikey";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($thelocation) .
'&key=' . $thekey;
$contextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$maps_json = file_get_contents($maps_url, 0, stream_context_create($contextOptions));// file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key='.$thekey;
//https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&rankby=distance&key=
$places_json = file_get_contents($places_url,0, stream_context_create($contextOptions));
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array["results"] as $item) {
echo $item["name"]."<br>";
}
}
this prints....easy
AVEonline.co
KRAV MAGA GLOBAL WORLD MAP
Mark Carvalho
Amyan
Moving the Planet
Sosta in Camper
NosCode
GLOBAL BUZZ
OptiClean
JI-SU TELECOM
Reel Thrillz
Clío Reconstrucción Histórica
AprimTek
Hayjayshop
NHAV
gitanos.cat
Being Digitall
Directory+
AdExperts
Optical Spectroscopy and Nanomaterials Group
The $lat,$lng variables or the API call is your first problem, and the foreach loop is the second.
The json_decode($someJSON, true); creates an associative array from your json, so you can't use the -> arrows, those are for the objects. More about this.
There's no $item->photo_reference, use:
$results = $places_array["results"];
foreach ($results as $item) {
echo $item["photos"]["photo_reference"];
}
I create a json object from mysqli query (db class).
class db
public function Json() {
$result = $this->db->mysqli->query
("SELECT * FROM table");
$data = array();
while($row = $result->fetch_array()) {
$data[]= array('id' => "" .$row[0]. "", 'text' => "" .$row[1]. "");
}
echo json_encode($data);
}
In my php page I set a data-variable getting the json object from my php class
index.php
$db = new db();
<input type="hidden" id="jsonObject" data-json='<?php $db->Json();?>'/>
and get the data with jquery in this way
<script>
var data = $.parseJSON($('#jsonObject').attr("data-items"));
</script>
This work well, but if I have a php json data with apostrophe like
[{"id":"1","text":"I don't know"},{etc..}]
I've this error
SyntaxError: missing ) after argument list
I tried to use addslashes function in php when I create the associative array but with no success.
$data[]= array('id' => "" .$row[0]. "", 'text' => "" .addslashes($row[1]). "");
The json object is displayed correctly in the html source, so I guess it's a problem with jquery.
How can I solve my problem? Thank you
I am trying to get propriety of Json Decoded string of twitch tv
$hue = file_get_contents('https://api.twitch.tv/kraken/streams/?channel=starladder1');
$hue = json_decode($hue);
print_r($hue->display_name);
but it doesnt work tryed almost everything please help
Try following code:
<?php
$hue = file_get_contents('https://api.twitch.tv/kraken/streams/?channel=starladder1');
$hue1 = json_decode($hue, TRUE);
foreach ($hue1 as $data)
{
foreach ($data as $datas) {
echo ($datas['channel']['display_name']."<br/>");
}
}
?>
the reason why it is not working is because you try to access "display_name" directly without analyzing the structure of the object.
Try this:
print_r($hue->streams[0]->channel->display_name);
You see that streams begins with an "[" which means that its elements are accessed like an array
Your object really looks like this, and this helps you to understand the structure better:
{
"streams":[{
"_id":10954982848,
"game":"Dota 2",
"viewers":11918,
"_links":{
"self":"https://api.twitch.tv/kraken/streams/starladder1"
},
"preview":{
"small":"http://static-cdn.jtvnw.net/previews-ttv/live_user_starladder1-80x50.jpg",
"medium":"http://static-cdn.jtvnw.net/previews-ttv/live_user_starladder1-320x200.jpg",
"large":"http://static-cdn.jtvnw.net/previews-ttv/live_user_starladder1-640x400.jpg",
"template":"http://static-cdn.jtvnw.net/previews-ttv/live_user_starladder1-{width}x{height}.jpg"
},
"channel":{
"_links":{
"self":"http://api.twitch.tv/kraken/channels/starladder1",
"follows":"http://api.twitch.tv/kraken/channels/starladder1/follows",
"commercial":"http://api.twitch.tv/kraken/channels/starladder1/commercial",
"stream_key":"http://api.twitch.tv/kraken/channels/starladder1/stream_key",
"chat":"http://api.twitch.tv/kraken/chat/starladder1",
"features":"http://api.twitch.tv/kraken/channels/starladder1/features",
"subscriptions":"http://api.twitch.tv/kraken/channels/starladder1/subscriptions",
"editors":"http://api.twitch.tv/kraken/channels/starladder1/editors",
"videos":"http://api.twitch.tv/kraken/channels/starladder1/videos",
"teams":"http://api.twitch.tv/kraken/channels/starladder1/teams"
},
"background":null,
"banner":null,
"display_name":"starladder1",
"game":"Dota 2",
"logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/starladder1-profile_image-557367f831a49ebb-300x300.png",
"mature":false,
"status":"NewBee vs LGD-Gaming 1:0 # WEC Lan-Finals Day 2 by v1lat",
"url":"http://www.twitch.tv/starladder1",
"video_banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/starladder1-channel_offline_image-c29311bb34830472-640x360.png",
"_id":28633177,
"name":"starladder1",
"created_at":"2012-03-01T18:05:14Z",
"updated_at":"2014-09-06T06:59:23Z",
"abuse_reported":null,
"delay":0,
"followers":118574,
"profile_banner":null,
"profile_banner_background_color":null,
"views":186419614,"language":"en"
}
}],
"_total":1,
"_links":{
"self":"https://api.twitch.tv/kraken/streams?channel=starladder1&limit=25&offset=0",
"next":"https://api.twitch.tv/kraken/streams?channel=starladder1&limit=25&offset=25",
"featured":"https://api.twitch.tv/kraken/streams/featured",
"summary":"https://api.twitch.tv/kraken/streams/summary",
"followed":"https://api.twitch.tv/kraken/streams/followed"
}
}
Here is code for you:
$hue = json_decode(file_get_contents('https://api.twitch.tv/kraken/channels/starladder1'));
echo "Name :" .$hue->display_name;
You just do wrong url to fetch