How Php To Json converted? - php

We can convert php code how to json format?
I may have not accurately PHP coding I am beginner to learn about it because I'm new . I'll integrated into Android application.
I also draw pictures about how the information ?
for example, I want to do something like this: http://mikepenz.com/android/unsplash/pictures
<?php
// don't forget to change 'username' to your actual tumblr name
$request = 'http://walltumbler.tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
// Tumblr JSON doesn't come in standard form, some str replace needed
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
// parameter 'true' is necessary for output as PHP array
$value = json_decode($input, true);
$content = $value['posts'];
// the number of items you want to display
$item = 98988;
// Tumblr provides various photo size, this case will choose the 75x75 square one
$type = 'photo-url-1280';
?>
{
"limit": null,
"offset": 0,
"count": 2442,
"total": 2442,
"data": [
<?php
for ($i=0;$i<=$item;$i++) {
if ($content[$i]['type'] == 'photo') {
echo '
{
"id": '.$i.';
"author": "Paul Jarvis",
"image_src": "' . $content[$i][$type] . '",
"color": "#7F7873",
"date": "2015-01-21 19:20:00",
"modified_date": "2014-09-01 22:36:53",
"width": 2500,
"height": 1667,
"ratio": 1.4997000694275,
"featured": 1,
"temp_id": 1
}';
$string = rtrim($item, ', ');
}
}
?>
]}

Try using the json_encode() function
<?php
$request = 'http://walltumbler.tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
$value = json_decode($input, true);
$content = $value['posts'];
$item = 98988;
$type = 'photo-url-1280';
$photos_array = array();
for ($i=0;$i<=$item;$i++) {
if ($content[$i]['type'] == 'photo') {
$photos_array[] = array(
'id' => $i,
'author' => 'Paul Jarvis',
// Continue with all your values...
);
}
}
$json_data = array(
'limit' => null,
'offset' => 0,
'count' => 2442,
'total' => 2442,
'data' => $photos_array
);
// Then use json_encode to get your json data...
echo json_encode( $json_data );
Hope it helps

Related

Struggling to convert to json string

I've got a textbox that the user can enter details into it in a csv format. So they would enter something like
user 1,user1#email.com
user 2,user2#email.com
user 3,user3#email.com
The out put of that when I dd(request('users')) is this
user 1, user1#email.com\n
user 2, user2#email.com\n
user 3, user3#email.com
What I would like is to save it in a json format so that it can end up looking like this
[
{
"name": "user 1",
"email": "user1#email.com"
},
{
"name": "user 2",
"email": "user2#email.com"
},
{
"name": "user 3",
"email": "user3#email.com"
}
]
I'm struggling to get it to be like how I would like it. I've tried json_encode(request('users')) but I ended up with
""user 1, user1#email.com\nuser 2, user2#email.com\nuser 3, user3#email.com""
I also tried this
$replace = preg_replace('/\n+/', "\n", trim(request('users')));
$split = explode("\n",$replace);
$json = json_encode($split);
but I got this
"["user 1, user1#email.com","user 2, user2#email.com", "user 3, user3#email.com"]"
The keys name and email you want in your result are not going to appear out of thin air, you need to create them.
Split the data into individual lines, loop over those lines.
Split each line into its two parts.
Create the necessary data structure, introduce the keys you want the data to be stored under at this point.
Encode the whole thing as JSON.
$data = 'user 1,user1#email.com
user 2,user2#email.com
user 3,user3#email.com';
$lines = explode("\n", $data);
$result = [];
foreach($lines as $line) {
$parts = explode(',', $line);
$result[] = ['name' => $parts[0], 'email' => $parts[1]];
}
echo json_encode($result);
You can simply use array_map to map each line to a key-value pair created by using array_combine:
$array = array_map(function($line) {
return array_combine(['name', 'email'], str_getcsv($line));
}, explode("\n", $request('users')));
$json = json_encode($array);
var_dump($json);
The result would be:
string(133) "[{"name":"user 1","email":"user1#email.com"},{"name":"user 2","email":"user2#email.com"},{"name":"user 3","email":"user3#email.com"}]"
Try this
$xx = "user 1, user1#email.com\nuser 2, user2#email.com\nuser 3, user3#email.com";
$xxx = explode("\n",$xx);
$res = [];
foreach($xxx as $y)
{
$new = explode(',',$y);
$res[] = [
'name' => $new[0],
'email' => $new[1]
];
}
echo json_encode($res,true);
Output will be
[
{
"name":"user 1","email":" user1#email.com"
},
{
"name":"user 2","email":" user2#email.com"
},
{
"name":"user 3","email":" user3#email.com"
}
]
Try this
$data = explode("\n", trim(request('users')));
$result = collect($data)->map(function ($row) {
$columns = explode(',', $row);
return [
'name' => $columns[0] ?? null,
'email' => $columns[1] ?? null
];
});

execute php echo as parameter value

I have below code & I am generating tracking_id values manually & its working fine :
<?php
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => "1234",
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Result :
{"response":[{"tracking_id":"1234",}],
Now i need to create tracking_id dynamically.... so i tried like below :
"tracking_id" => "$r = 'DOCC'. mt_rand(0000000001,9999999999); echo $r;",
I got below Result :
{"response":[{"tracking_id":" = 'DOCC'. mt_rand(0000000001,9999999999); echo ;","
But i should get some random number as tracking_id....
Means php code inside parameter is not working....
As your require 10 digit random number:
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(1, 9);
}
return $result;
}
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'.randomNumber(10);//no need to echo, just assign it
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Refactor your code:
$r = 'DOCC'. mt_rand(0000000001,9999999999);
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => $r,
];
Just replace $data array with the following.
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'. mt_rand(0000000001,9999999999),
];

telegram bot split keyboard rows[columns]

I am writing my telegram bot codes in PHP. I would like to split my inline keyboard into 2 or 3 columns. Here is my code:
foreach ($categories as $cat) {
$key[] = array(
array('text'=>$cat['name'],'callback_data'=>'sub-'.$cat['id'])
);
if ($k % 2 == 0) {
$keyoptions[] = $key;
$key = array();
}
$k++;
}
$telegram->SendMessage($userid, $keyoptions);
but my code doesn't work. Where is the problem and how can I solve my issue?
EDIT :
i just used this code
$keyoptions = array_chunk($keyoptions,3);
but still can't find the problem;
Telegram API: inline_keyboard: Array of Array of InlineKeyboardButton
Example:
keyboard: [
["uno :+1:"],["uno \ud83d\udc4d", "due"],["uno", "due","tre"]
]
I don't know what library you are using and what are those fields in your code, but this a working with native telegram API:
function inlineKeyboard($text, $chatID, $btnNames, $callBackDatas)
{
$inlineRow = array(); // this is array for each row of buttons
$i = 0;
foreach ($btnNames as $name) {
array_push($inlineRow, array("text" => $name, "callback_data" => $callBackDatas[$i]));
$i++;
}
/* if you need multiple rows then just create other inlineRow arrays
and push to this array below */
$inlineKeyboard = array($inlineRow);
$keyboard = array(
"inline_keyboard" => $inlineKeyboard
);
$postfields = array
(
'chat_id' => "$chatID",
'text' => $text,
'reply_markup' => json_encode($keyboard)
);
send('sendMessage', $postfields);
}
define('BaseURL', 'https://api.telegram.org/bot<TOKEN>');
function send($method, $datas)
{
$url = BaseURL . "/" . $method;
if (!$curld = curl_init()) {
exit;
}
curl_setopt($curld, CURLOPT_POST, true);
curl_setopt($curld, CURLOPT_POSTFIELDS, $datas);
curl_setopt($curld, CURLOPT_URL, $url);
curl_setopt($curld, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curld);
curl_close($curld);
return $output;
}

PHP - remove HTML-attributes from string in JSON

I have a JSON-response from embed.ly which I get in my PHP-script like this:
// jSON URL which should be requested
$json_url = 'http://api.embed.ly/1/oembed?key=hidden&url='.$_POST['url'];
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
My problem is that I want the responses from embed.ly embedded in my responsive layout, but embed.ly-responses of videos include with & height attributes:
{"provider_url": "http://www.youtube.com/", "description": "Markus Eisenrings Stromboli electric car on swiss television broadcast. See www.stromboli.ch for more information.", "title": "Stromboli Electric Car", "url": "http://www.youtube.com/watch?v=TJCZnpHuFS8", "author_name": "hangflug", "height": 360, "thumbnail_width": 480, "width": 640, "html": "<iframe width=\"640\" height=\"360\" src=\"http://www.youtube.com/embed/TJCZnpHuFS8?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>", "author_url": "http://www.youtube.com/user/hangflug", "version": "1.0", "provider_name": "YouTube", "thumbnail_url": "http://i1.ytimg.com/vi/TJCZnpHuFS8/hqdefault.jpg", "type": "video", "thumbnail_height": 360}
I tried removing all width & height-attributes from that JSON-string like this:
$result = json_encode(preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i', '<$1$4$7>', json_decode($result)));
However, this is giving me a PHP-error.
Catchable fatal error: Object of class stdClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/projectname/ajax.php on line 22
Any ideas?
Can't you just do this:
$arr = json_decode($result, true);
unset($arr["height"], $arr["width"]);
$result = json_encode($arr);
UPDATE: For your specific example:
$arr = json_decode($result, true);
unset($arr["height"], $arr["width"]);
$arr_temp = explode(' ', $arr["html"]);
foreach ($arr_temp as $i => $val) {
if ((substr($val, 0, 7) != "height=") && (substr($val, 0, 6) != "width="))
$arr_html[] = $val;
}
$arr["html"] = implode(' ', $arr_html);
$json_result = json_encode($arr);
PHP Sandbox
finally got it to work with help form here like this:
$arr = json_decode($result, true);
foreach ($arr as $key => & $val) {
if($key=='html'){
$html = preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i','<$1$4$7>', $arr['html']);
$arr[$key] = $html;
}
}
$result = json_encode($arr);

Array of Freebase MIDs and sending multiple queries to freebase

I want to loop through the MySQL results which is an array of Freebase MIDs and I want the output to be the names of the Freebase article!
Here's my code:
$query = "SELECT `mid` FROM `items`";
$result = mysql_query($query);
$count = 1;
while ($row = mysql_fetch_array($result)) {
$mid = $row['mid'];
$simple_query = array('name'=> null, 'mid'=>$mid);
$q_array = array('q'.$count=>array('query'=>$simple_query));
array_push ($query_array, $q_array );
$count++;
}
$jsonquerystr = json_encode($query_array);
$apiendpoint = "http://api.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch);
$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an array
foreach($resultarray as $name){
echo "$name<br>";
}
error:
{ "code": "/api/status/error", "messages": [ { "code": "/api/status/error", "message": "'list' object has no attribute 'get'" } ], "status": "500 Internal Error", "transaction_id": "cache;cache04.p01.sjc1:8101;2012-05-14T07:31:39Z;0079" }
Your $query_array should just be an associative array of queries by name rather than an array of associative arrays. So instead of this:
$q_array = array('q'.$count=>array('query'=>$simple_query));
array_push ($query_array, $q_array );
..it should look something like this:
$q_array = array('query'=>$simple_query);
$query_array['q'.$count] = $q_array;
However, that code is using the old Freebase API which is about to be deprecated. A better way to do this in the new API would be to structure it all as one query like this:
[{
"mid": null,
"name": null,
"topics:mid|=":[
"/m/045c7b",
"/m/0d6lp",
"/m/021ympy",
...
]
}]
This lets you pass in an array of MIDs and get back a name for each one. The URL to fetch this from the new API should look something like this:
https://www.googleapis.com/freebase/v1/mqlread/?query=[{...}]

Categories