Adding JSON to PHP file - php

I am trying to add a JSON script to a php file in my sites admin. My goal is to have the JSON run when the order status is change to 3 (shipped).
I am pretty sure I am going about this all wrong but I am not sure what to do yet. here is my code:
if ( ($check_status['orders_status'] != $status) && $check_status['orders_status'] == 3) { ?>
<script>
POST https://api.yotpo.com/oauth/token
{
"client_id": "### Your client_id ###",
"client_secret": "### Your client_secret ###",
"grant_type": "client_credentials"
}
POST https://api.yotpo.com/myapi/purchases
{
"validate_data": true,
"platform": "general",
"utoken": "### YOUR UTOKEN ###",
"email": "client#abc.com",
"customer_name": "bob",
"order_id": "order_1",
"order_date": "2010-10-14",
"currency_iso": "USD",
"products": {
"SKUaaa12": {
"url": "http://example_product_url1.com",
"name": "product1",
"image": "http://images2.fanpop.com/image/photos/13300000/A1.jpg",
"description": "this is the description of a product",
"price": "100",
"specs": {
"upc": "USB",
"isbn": "thingy"
},
"product_tags": "books"
}
}
}
</script>
<?php } ?>
First of all, there is nothing in my code that says hey, this is JSON besides the tag.
do I need to have the json in a sepearate json file? Or do I need to convert this script to php?

First of all, Nikita is correct that JSON does not run - it is not script. It is a standardized way to store information.
PHP has native JSON handling functions and can easily take existing objects or arrays and convert them to JSON.
<?php
$json = json_encode($my_data);
?>
<input type="hidden" name="post_data" <?php echo 'value="'.$json.'" ?> />
Then when you send this variable $json to the next page, you'll unpack it like so
$my_data = json_decode($_POST['post_data']);
This is a pure PHP implementation, though JavaScript does nice functions to stringify to/from json as well.

Related

Valid JSON from text file

I understand there are other similar posts about this, I am going out of my wits end here.
I have a few files with some JSON (all valid according to online validators, eg. jsonlint) - see EDIT below.
$contents = file_get_contents(DATA_PATH.'/'.$type.'.json');
$data = json_decode($contents, true);
echo var_dump($data);
Returns NULL
If I echo $contents, I do get output.
I'm not sure what is wrong? I understand file_get_contents gets it into a string, however, how do I get it in a valid JSON? Would using fopen() be any different?
I even added the JSON to a variable but had the same outcome... I must be stupid.
Note: Most JSON I'll get will be from an API, these file-based JSONs are for testing purposes.
Thanks.
EDIT: Sample json
{
"data": [{
"id": 1,
"name": "Albania",
"alpha2code": "AL",
"alpha3code": "ALB",
"capital": "Tirana",
"flag": "https://cdn.elenasport.io/flags/svg/1",
"region": "Europe",
"subregion": "Southern Europe",
"timezones": [
"UTC+01:00"
]
},
{
"id": 3,
"name": "Algeria",
"alpha2code": "DZ",
"alpha3code": "DZA",
"capital": "Algiers",
"flag": "https://cdn.elenasport.io/flags/svg/3",
"region": "Africa",
"subregion": "Northern Africa",
"timezones": [
"UTC+01:00"
]
}]
}
Your file might have a UTF-8 BOM which is not copied when you copy-and-paste your sample JSON to a (web based) validator. It's an invisible mark at the beginning of your file.
If you run echo bin2hex(file_get_contents(DATA_PATH.'/'.$type.'.json')) your file should begin with 7b, which is a {.
If it starts with efbbbf and then a 7b, there is a BOM. Either strip it out yourself or re-save your JSON without one using a text editor like Sublime Text which allows you to configure that.

json - how to get data from json where user's input will come on %s [duplicate]

This question already has answers here:
PHP replace wildcards (%s, %d) in string with vars
(2 answers)
Closed 3 years ago.
I've got a JSON file which looks like this
{
"facebook": {
"icon": "fab fa-facebook",
"title": "Facebook",
"url": "https://facebook.com/%s"
},
"instagram": {
"icon": "fab fa-instagram",
"title": "Instagram",
"url": "https://instagram.com/%s"
}
}
So I'm getting users social links from a form, but only the user's ID of social link eg.https://facebook.com/ID. I'm storing the users ID in JSON file in database. I'm using PHP. How do I add the users ID in that '%s' and display the link.
To put together the information using the JSON data you have, you would use either sprintf() or printf() (the only difference being the printf() directly outputs the data sprintf() returns a string). The information on the manual pages shows how things like %s works.
So the code would look something like...
$id = 123;
$userName = "User name";
$json = '{
"facebook": {
"icon": "fab fa-facebook",
"title": "Facebook",
"url": "https://facebook.com/%s"
},
"instagram": {
"icon": "fab fa-instagram",
"title": "Instagram",
"url": "https://instagram.com/%s"
}
}';
$socialMedia = json_decode( $json, true );
echo echo '<a href="'.sprintf($socialMedia["facebook"]["url"], $id).'">'.
$userName.'</a>';
Which outputs...
User name

Iterating through this JSON string in PHP

This is my file, titled parks.JSON:
{
"state": [
{
"name": "Alabama",
"park1": "Bladon Springs State Park",
"park1Link": "http://www.stateparks.com/bladon_springs_state_park_in_alabama.html",
"park2": "Florala State Park",
"park2Link": "http://www.stateparks.com/florala_state_park_in_alabama.html"
},
{
"name": "Alaska",
"park1": "Chugach State Park",
"park1Link": "http://www.stateparks.com/chugach_state_park_in_alaska.html",
"park2": "Kachemak Bay State Park",
"park2Link": "http://www.stateparks.com/kachemak_bay_state_park_in_alaska.html"
}
]
}
And this is my php embedded in an html file to call it:
$json_url = "../data/parks.JSON";
$parksJSON = file_get_contents($json_url);
$parksData = json_decode($parksJSON, TRUE);
I am not sure how to go about iterating through my array. I, of course, will have all 50 states entered here in theory.
I have read other posts asking this and their methods don't work because my JSON format is always different from theirs it seems!
I would have thought a pretty simple loop would do it
foreach ($parksData["state"] as $state)
{
echo $state["name"];
}

creating json object from sql database using php

I am trying to create a json object from my mysql database for a android project. I need an output something like this:
{
"feed": [
{
"id": 1,
"name": "National Geographic Channel",
"image": "http://api.androidhive.info/feed/img/cosmos.jpg",
"status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
"profilePic": "http://api.androidhive.info/feed/img/nat.jpg",
"timeStamp": "1403375851930",
"url": null
},
{
"id": 2,
"name": "TIME",
"image": "http://api.androidhive.info/feed/img/time_best.jpg",
"status": "30 years of Cirque du Soleil's best photos",
"profilePic": "http://api.androidhive.info/feed/img/time.png",
"timeStamp": "1403375851930",
"url": "http://ti.me/1qW8MLB"
}
]
}
But I am getting ouput something like this:
{"feed":[{"id":"0","name":"punith","image":"","status":"ucfyfcyfffffffffffffffffffffffffffffffff","profilePic":"http:\/\/api.androidhive.info\/feed\/img\/nat.jpg","timestamp":"1403375851930","url":""}]}
Everything is on a single line and the id attribute should not be quotes. Is there anything I could do.This is my php file
<?php
define('HOST','');
define('USER','');
define('PASS','');
define('DB','');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from timeline";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>$row[0],
'name'=>$row[1],
'image'=>$row[2],
'status'=>$row[3],
'profilePic'=>$row[4],
'timestamp'=>$row[5],
'url'=>$row[6]
));
}
echo json_encode(array("feed"=>$result));
mysqli_close($con);
?>
And will it affect if the output is on a single line.
The database contains exactly the same columns used as attributes.
Thanks in advance
ID in quotes
ID is in quotes because it is a string, not an integer. You can change that by changing this:
array('id'=>$row[0]
to this:
array('id'=>intval($row[0])
"Pretty Printing"
Putting it on multiple lines will only affect readability but not how the data is computed - but you can prettify it: Pretty-Printing JSON with PHP
$output = json_encode(array("feed"=>$result), JSON_PRETTY_PRINT);
echo $output;
Try encoding with JSON_PRETTY_PRINT
$json_string = json_encode($data, JSON_PRETTY_PRINT);
where data is your result array.
in your case
echo json_encode(array("feed"=>$result),JSON_PRETTY_PRINT);
refer this Tutorial from the official PHP docs .
Aswell as the other answers, it would be more semantic to include the json header, I've found that just including this also helps with the appearance of the json itself so that it is formatted properly and not all one continuous string.
header('Content-Type: application/json');
For php>5.4
$json=json_encode(array("feed"=>$result),JSON_PRETTY_PRINT);
header('Content-Type: application/json');
print_r($json);

php - Send data from one php page to another and refresh it with the new data

i'm trying to the following:
I have 1 page that is called request.php that receives a post from a webhook of hipmob
Documentation: https://www.hipmob.com/documentation/chat-events.html
<?php
$entityBody = file_get_contents('php://input');
$post_data = $_POST;
$data = json_encode($post_data, JSON_PRETTY_PRINT);
$file = 'webhook.txt';
$current = file_get_contents($file);
file_put_contents($file, $data);
//error_log($data);
?>
Example output:
{
"app": "eba978375b294260bd884a72afd5eb75",
"appname": "Worten Suporte",
"event": "chat.message",
"started": "2015-06-12T08:32:56+00:00",
"ip": "62.28.231.158",
"platform": "Windows\/Chrome",
"version": "43",
"timestamp": "2015-06-12T09:32:36+00:00",
"body": "mensagem",
"properties": "{\"as\":\"text\"}",
"id": "70acc6b20cbc44f18f99e2e922130904",
"email": "eba978375b294260bd884a72afd5eb75.70acc6b20cbc44f18f99e2e922130904#app.hipmob.com",
"visits": "1",
"locale": "pt",
"userdata:context": "viewing file:\/\/\/C:\/Users\/hp\/Desktop\/chattest.html title: ;url: file:\/\/\/C:\/Users\/hp\/Desktop\/chattest.html",
"state": "",
"signature": "622869e9210ba4599e95322cafd7f8123552375b44314e502ceb53972f9bfadb1a49d965f3102d8f30028690bc606632c6878e4ff95003ec15c0ea2749a8bd84"
}
I want to know if its possible everytime i receive a post in this page i get a notification in other page let's say:
example.php
and refresh it with the new data
To do that you need to maintain last inserted row with a visibility flag.
After that you will have to call ajax (on example.php) after a particular interval by using settimeout. In that ajax call you can compare the visibility flag and refresh the page.
You should store the data you received from hipmob in a database with lets say a flag 'seen'.
Then you could create an AJAX call from the example.php page to get notifications that haven't been seen yet in the database and the refresh the data based on that.

Categories