how to convert this json data in php - php

I am using an api which is giving me a very strange json format.. i'm posting its data which i am getting thru it..
info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "f53762dab34022e9d851ab71e0bf166f" };
I'm trying to print this data in php but i'm not able to do that..nothing is showing on my webpage,....
My code are..
First i tried,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
echo $info;
?>
My second attempt was,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
$info->h;
?>
My last attempt was,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
$info['h'];
?>
Nothing is happening..
please somebody help me
API Url converted...

The page is sending
"info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "058ce93db26fce4a9f1cb41ae2e7c1bb" };"
You cannot use json_decode on this because the info = and the ; at the end are not json. You have to strip the info = and the ;.
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info = file_get_contents($url);
$info = trim($info, "info = ");
$info = rtrim($info, ";");
$json = json_decode($info, true);
echo $json['status'];

The data I got from the URL in your example is
info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "5cddd4d1667f24aa9a0f5a6cc21e24e3" };
That's an executable JavaScript snippet, not actually JSON. The reason your php is failing is due to the 'info =' part... json_encode returns null on decoding failure.
While this is an assignment of a variable to a JavaScript object, that would work as JSON too if you removed the 'info =' and semicolon. Assuming the responses are predictable, you could do this with php str_replace, but finding an API that returns JSON for your source would be a more reliable and clean solution.

If you're getting NULL when you var_dump($info) on the second line as you mentioned in comments, then file_get_contents() doesn't retrieve the data.
It's most likely because allow_url_fopen is set to false in PHP.ini

From the json_decode() documentation:
Takes a JSON encoded string and converts it into a PHP variable.
If 2nd parameter is set to true it returns an array !
SO your first and second attempt is wrong.! It should work third attempt. Just check if you retrieve the data.

Related

Get JSON from a URL by PHP

I have a URL that returns a JSON object like this:
{
"USD" : {"15m" : 7809.0, "last" : 7809.0, "buy" : 7809.85, "sell" : 7808.15, "symbol" : "$"},
"AUD" : {"15m" : 10321.42, "last" : 10321.42, "buy" : 10322.54, "sell" : 10320.3, "symbol" : "$"},
}
URL : https://blockchain.info/ticker
more info : https://blockchain.info/api/exchange_rates_api
I want to get all the data from the first line and echo it and to have it keep requesting it so its live
I have used the examples on git hub
https://github.com/blockchain/api-v1-client-php/blob/master/docs/rates.md
but it displays all of the data output and you have to refresh it to get it updated
please can some one point me in the right direction
ideally I would end up with something like
15 m Last Buy Sell
USD ($) 7794.87 7794.87 7795.72 7794.02
I have the table and data going to the table but its echoing the whole data set rather than the first line and also I dont know how to select individual fields
How can I do it through PHP?
What you need is a request php page, which will make:
1 - Get data from te site:
$data = file_get_contents('https://blockchain.info/ticker');
2 - decode the json
$decodedData = json_decode($data);
3 - Here you can access it using OOP:
var_dump($decodedData->USD);
The point here will be to retrieve data as you wish, you can mix it up with HTML in a table for example.
Then, you need a JS script, that will execute a function with setInterval, each few miliseconds. That function should make a request to a PHP page that you created earlier, get that data and change with the updated one.
This Should do it:
<?
$seconds = 5;
function get_live_quote($key){
$json_string = file_get_contents('https://blockchain.info/ticker');
$json_array = json_decode($json_string, TRUE);
$quote = $json_array[$key];
$keys = implode(" ",array_keys($quote));
$values = implode(" ", array_values ($quote));
return "$keys $values \n";
}
while(TRUE){
echo get_live_quote("USD");
sleep($seconds);
}
Save the preceding code to a file like "quote.php". Then from your terminal just run: php quote.php

How Do I read CloudKit Errors?

I have a php script that's trying to create a record in a CloudKit database.
It returns this error:
object(stdClass)#1 (3) { ["uuid"]=> string(36)
"c70072a1-fab6-491b-a68f-03b9056223e1" ["serverErrorCode"]=>
string(11) "BAD_REQUEST" ["reason"]=> string(62)
"BadRequestException: Unexpected input at [line: 2, column: 10]" }
I presume this tells me exactly what the problem is, but I don't know how to interpret it. Where is line 2 and column 10?
I think its related to the JSON I'm sending in the create record request.
$url = 'https://api.apple-cloudkit.com/database/1/' . $CONTAINER . '/development/public/records/modify';
$opDict = '{"operationType": "create",
"record":"Artists",
"fields": {"firstName":{"value":"Mei"},
"lastName": {"value":"Chen"},
"principalDiscipline": {"value":""},
"secondaryDiscipline":{"value":""}},
"recordName":"Mei Chen"}';
$body = '{"operations":['.$opDict.']}';
echo $body;
When I check the output from $body
{"operations":[{"operationType": "create", "record":"Artists",
"fields": {"firstName":{"value":"Mei"}, "lastName": {"value":"Chen"},
"principalDiscipline": {"value":""},
"secondaryDiscipline":{"value":""}}, "recordName":"Mei Chen"}]}
it passes JSON lint, so I am not sure it is a JSON problem.
Can someone explain to me how to interpret the error I'm getting from CloudKit. The docs are a little vague on errors.
I got absolutely no clue about CloudKit, but I found this documentation page with the followin example:
{
"operationType" : "create",
"record" : {
"recordType" : "Artist",
"fields" : {
"firstName" : {"value" : "Mei"},
"lastName" : {"value" : "Chen"}
}
"recordName" : "Mei Chen"
},
}
which definitely differs from what you try to send, both in terms of data structure
(your record is not a dictionary) and content (you have no recordType).
So while your JSON is syntactically correct, you are simply sending invalid content data wrapped in valid JSON which is most likely the reason you are seeing the error message.

JSON object passed in the php script [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a PHP script and JSON object with some values is being passed in the the PHP get function. I have tried different ways to decode JSON but failed.
The code I have tried is :
$get_order_info = $_GET['orderInfo'];
$order_json = json_decode($get_order_info, true);
echo $order_json->{'mealsInfo'};
The JSON string is :
{
"mealsInfo" : [
{
"DrinkSize" : 1,
"MealQuantity" : 1,
"MealId" : "57",
"addons" : [
{
"addOnID" : 1,
"addonTitle" : "spicy"
},
{
"addOnID" : 3,
"addonTitle" : "Thin Base"
}
],
"FriesSize" : 2
}
],
"TransactionID" : "56",
"OrerType" : "PickUp",
"frenchiseInfo" : {
"storeName" : "Dubai Downtown Franchise",
"OrderCollectionTime" : "06:12:50 PM",
"FranchiseId" : "4"
},
"customerinfo" : {
"Instructions" : "Test instruction",
"CustomerName’" : "Talat",
"Area" : "al Riga",
"City" : "Dubai",
"Phone" : "0559467800",
"Email" : "test#test.com",
"Address" : "al nouf tower"
},
"status" : "pending",
"totalPrice" : 51
}
Can somebody please help me to decode it in a correct way?
Thanks in advance !
You are passing true as second parameter to json_decode, it will return and array not object. Try with -
$order_json = json_decode($get_order_info, true);
echo $order_json['mealsInfo'][0]['DrinkSize'];
$get_order_info = $_POST['orderInfo'];
$order_json = json_decode($get_order_info, true);
echo $order_json->{'mealsInfo'};
Try this.
$order_json = json_decode($get_order_info, true);
var_dump($order_json->{'mealsInfo'});

Error executing phantom js on windows . Invalid json

I am using phantom library to convert my highcharts to PDF.
When I execute the code
$result = json_decode(trim(shell_exec($this->getBinPath() . ' ' . escapeshellarg(json_encode($args)))));
Error is returned saying
unable to parse json
Command being run is
"C:\www\myproject\vendor\kriansa\h2p\bin/win32/phantomjs.exe" "C:\www\myproject\vendor\kriansa\h2p\bin/converter.js" "{ destination : C:\\Windows\\TEMP\\14b6e6edc209b6e731bdbc79976a9430438409ae.tmp , request :{ uri : C:\\Windows\\TEMP\\127ef8f78c335d9af694a9cef0423541dd17a256.html , method : GET }, orientation : Portrait , format : A3 , zoomFactor :1, allowParseCustomFooter :false, allowParseCustomHeader :false, border : 1cm , header :null, footer :null}"
What should I check for ? I have validated the json being passed as argument.
Edit
I checked this also
"C:\www\cimba_aboutmy360\vendor\kriansa\h2p\bin/win32/phantomjs.exe" "C:\www\cimba_aboutmy360\vendor\kriansa\h2p\bin/converter.js" {"destination":"C:\\Windows\\TEMP\\d4ca24267110d5c234b7a006f1ae5c03da248e88.tmp","request":{"uri":"C:\\Windows\\TEMP\\9b5d4d28689c3bc00afc0831666d6ee39a934b5c.html","method":"GET"},"orientation":"Portrait","format":"A3","zoomFactor":1,"allowParseCustomFooter":false,"allowParseCustomHeader":false,"border":"1cm","header":null,"footer":null}
same error again
I'm using this tool to validate JSON for JS, it has to pass the JS eval tests.
This JSON parses correctly:
{
"destination" : "C:\\Windows\\TEMP\\14b6e6edc209b6e731bdbc79976a9430438409ae.tmp",
"request":
{
"uri" : "C:\\Windows\\TEMP\\127ef8f78c335d9af694a9cef0423541dd17a256.html",
"method" : "GET"
},
"orientation" : "Portrait",
"format" : "A3",
"zoomFactor" :1,
"allowParseCustomFooter" :false,
"allowParseCustomHeader" :false,
"border" : "1cm",
"header" :null,
"footer" :null
}
Notice the quotes around they keys (destination, etc) and quotes around non-native types and strings. You can leave null, boolean, integers, decimals without quotes.
Edit
I think you also need to wrap the JSON in quotes in the command call
"C:\www\cimba_aboutmy360\vendor\kriansa\h2p\bin/win32/phantomjs.exe"
"C:\www\cimba_aboutmy360\vendor\kriansa\h2p\bin/converter.js"
"{'destination':'C:\\Windows\\TEMP\\d4ca24267110d5c234b7a006f1ae5c03da248e88.tmp','request':{'uri':'C:\\Windows\\TEMP\\9b5d4d28689c3bc00afc0831666d6ee39a934b5c.html','method':'GET'},'orientation':'Portrait','format':'A3','zoomFactor':1,'allowParseCustomFooter':false,'allowParseCustomHeader':false,'border':'1cm','header':null,'footer':null}"

Leading slashes in JSON from Google Finance API call

I've been using the Google Finance API to successfully gather some stock info. The problem is that after a call to http://www.google.com/finance/info?infotype=infoquoteall&q=[$tickerSymbol], the JSON that Google returns has // added before it and therefore the string cannot be encoded using PHP's json_encode(). The JSONLint JSON Validator confirms that the //s are not valid. The obvious workaround is to strip the slashes from the beginning of the JSON. None-the-less, I am left wondering why Google is adding slashes to the JSON it is returning. Is there a purpose behind the extra slashes? Is this a quirk with PHP's json_encode() when other languages would simply ignore the extra characters? Am I doing something incorrectly?
Here is an example of the result of a request for http://www.google.com/finance/info?infotype=infoquoteall&q=AAPL with the leading slashes.
// [ {
"id": "22144"
,"t" : "AAPL"
,"e" : "NASDAQ"
,"l" : "340.65"
,"l_cur" : "340.65"
,"ltt":"4:00PM EST"
,"lt" : "Jan 18, 4:00PM EST"
,"c" : "-7.83"
,"cp" : "-2.25"
,"ccol" : "chr"
,"el": "345.20"
,"el_cur": "345.20"
,"elt" : "Jan 18, 5:45PM EST"
,"ec" : "+4.55"
,"ecp" : "1.34"
,"eccol" : "chg"
,"div" : ""
,"yld" : ""
,"eo" : ""
,"delay": ""
,"op" : "327.05"
,"hi" : "344.76"
,"lo" : "326.00"
,"vo" : "66.34M"
,"avvo" : "11.28M"
,"hi52" : "348.48"
,"lo52" : "190.25"
,"mc" : "313.75B"
,"pe" : "22.49"
,"fwpe" : ""
,"beta" : "1.38"
,"eps" : "15.15"
,"name" : "Apple Inc."
,"type" : "Company"
}
]
For those looking for a ready answer, here is a working example with PHP; The JSON is cleaned and transformed into an object. Values can easily be extracted.
The second is just to make it more awesome, it sends a push message you a PubNub channel when page is accessed (cron is your friend). PubNub message can easily be received via javascript hence live...
<?php
//Obtain Quote Info
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXDB:DAX');
//Remove CR's from ouput - make it one line
$json = str_replace("\n", "", $quote);
//Remove //, [ and ] to build qualified string
$data = substr($json, 4, strlen($json) -5);
//decode JSON data
$json_output = json_decode(utf8_decode($data));
// get the last price
$last = $json_output->l;
//Output Stock price .
echo 'DAX: ' . $last;
//////////////////////////////
// send it through pubnub //
//////////////////////////////
require_once('Pubnub.php');
// Publish and Subscribe Keys
$publish_key = 'demo';
$subscribe_key = 'demo';
$subscribe_key = false;
// Create Pubnub Object
$pubnub = new Pubnub( $publish_key, $subscribe_key, $secret_key );
// Publish !
$channel = 'quoteTheDax';
$timestamp = $pubnub->time();
$pubish_success = $pubnub->publish(array(
'channel' => $channel,
'message' => array("last" => $last2, "ts" => $timestamp)
));
//Boom its send to ppl subscribed to this channel arround the world
?>
of course if you need something live updating all the time there are better options. I was just looking to update every 30min/60min.
I guess it's because google don't want you to work with that JSON, they recommend to use the Google Data API.

Categories