Fetch, Decode and Re-encode JSON - php

I am attempting to fetch JSON from Instagram according to a number of URL parameters, the JSON is then decoded and then the objects required are then encoded into my own JSON format. Whilst I know this sound a little ridiculous, it is what is required. My only issue here is that for some reason it does not encode each section of JSON, it will only work for one item. The code is as below.
<?php
function instagram($count=16){
$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];
$url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;
$jsonData = json_decode((file_get_contents($url)));
$jsonData = json_decode((file_get_contents($url)));
foreach ($jsonData->data as $key=>$value) {
$response = array();
$response["data"] = array();
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
$result = json_encode($response);
}
return $result;
}
echo instagram();
?>
It will work for each section of JSON if I do something like this instead:
$result .= '<li>
'.$value->caption->from->username.'<br/>
'.$value->caption->from->profile_picture.'<br/>
'.$value->caption->text.'<br/>
'.$value->images->standard_resolution->url.'<br/>
'.$value->caption->created_time.'<br/>
</li>';
I feel I have bodged up somewhere with the array, however i'm not entirely sure.

What if we move $response["data"] and $result varia out of foreach?
Have you tried this?
$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
}
$result = json_encode($response);
return $result;

Related

Push array into array then encode - PHP

I'm trying to combine a few mySQL queries in a single PHP and push it all into a single JSON object.
So, I'm starting with the first query...like this:
$data=[];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_count = count($response);
$data['count'] = $final_count;
If I then do echo json_encode($data); I get a nicely formatted object like: {"count":61}
I then have a second query that I put the results through a loop, like so:
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$items = array();
foreach ($response as &$value) {
$items[] = $value['date_added'];
}
echo json_encode($items);
And I get my nice set of dates:
["2017-06-24 00:08:58","2017-06-26 15:01:48","2017-06-27 15:01:48","2017-06-28 23:19:41","2017-06-29 01:38:07","2017-06-30 00:08:58"]
Here's the question, how do I get this all back together like so:
{
"count": 61,
"dates": [
"2017-06-24 00:08:58",
"2017-06-26 15:01:48",
"2017-06-27 15:01:48",
"2017-06-28 23:19:41",
"2017-06-29 01:38:07",
"2017-06-30 00:08:58"
]
}
You could use
$myData['count'] = $final_count;
$myData['dates'] = $items
echo json_encode($myData);
$data=[];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_count = count($response);
// first store count in `$data`
$data['count'] = $final_count;
$data['dates'] = [];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
// next, store dates in subarray of `$data`
foreach ($response as &$value) {
$data['dates'][] = $value['date_added'];
}
// finally encode everything
echo json_encode($data);
Of course you can use array_merge of all your collected data.
Or:
$data=[];
// get $final_count
$data['count'] = $final_count;
// ... do some more stuff
// load items from db
$data['dates'] = $items;
echo json_encode($data);

Json wont response my array in php

I am trying to fetch multiple rows from my database and then encode them with json so I can access them in my Android application. I've successfully encoded an object but I couldn't find a way to do the same with an array. My code looks like:
if ($tag == 'friends') {
$id = $_POST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
$response[ "error"] = FALSE;
$result[] = array(
$response["friends"]["unique_id"] = $row["unique_id"],
$response["friends"]["name"] = $row["name"],
$response["friends"]["email"] = $row["email"]);
}
echo json_encode($response);
}
The code from getMyFriends($id) I have already tested and it works fine. It returns :
$result = mysql_fetch_array($result);
return $result;
When using a rest client passing the parameters:
Tag: friends
id: $id
this is the json response that I get:
{
"tag": "myfriends",
"error": false
}
, but no actual database data.
If anyone knows what I'm doing wrong, I'd really appreciate it, I've been browsing the internet for hours now.
If getMyFriends already have a $result = mysql_fetch_array($result);you don't need to fetch again.
You could simply:
$friends = $db->getMyFriends($id);
echo json_encode($friends);
But that will only return one friend, if you want all remove $result = mysql_fetch_array($result); from getMyFriends and return the pure mysql_result, then do something like:
$result = array();
while($row = mysql_fetch_assoc($friends)){
array_push($result,$row);
}
echo json_encode($result);
I tried this and it worked.
if($tag=='friends'){
$id = $_REQUEST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
$response[ "error"] = FALSE;
$result[] = array(
$response["friends"]["unique_id"] = $row["id"],
$response["friends"]["name"] = $row["name"],
$response["friends"]["email"] = $row["email"]
);
}
echo json_encode($result);
}
}

Get specific data from json using php

This is json data i received:
{"id":"8","cardnum":"5678887","point_collected":"26","date":"2015-05-06"}
{"id":"15","cardnum":"3435435","point_collected":"20","date":"2015-05-04"}
{"id":"11","cardnum":"5678887","point_collected":"50","date":"2015-05-03"}
{"id":"12","cardnum":"5678887","point_collected":"80","date":"2015-05-02"}
{"id":"14","cardnum":"5678887","point_collected":"10","date":"2015-05-02"}
I want to get the "cardnum" for comparison with my $usercard, and display all the result with the same "cardnum" and encode into json again.
This is my current code:
$decodeTrans=json_decode($transJson, true);
$response = array();
$usercard = "5678887";
foreach ($decodeTrans as $dt)
{
$membercard = $dt['cardnum'];
if ($membercard == $usercard)
{
$response["success"] = 1;
$response ['id'] = $dt['id'];
$response ['card_number'] = $membercard;
$response ['point_collected'] = $dt['point'];
$response ['date'] = $dt['date'];
echo json_encode($response);
}
}
}
}
I get this error: Invalid argument supplied for foreach()
Anyone can help? Thanks in advance.
Your input is not a valid JSON string. However, each line is still a valid JSON string. Update your code to split the $transJson and convert each line to PHP object using json_decode:
$response = array();
$usercard = "5678887";
foreach(explode("\n", $transJson) as $line)
{
$dt = json_decode(trim($line), true);
$membercard = $dt['cardnum'];
if ($membercard == $usercard)
{
$response["success"] = 1;
$response ['id'] = $dt['id'];
$response ['card_number'] = $membercard;
$response ['point_collected'] = $dt['point_collected'];
$response ['date'] = $dt['date'];
echo json_encode($response);
}
}
The demo: http://sandbox.onlinephpfunctions.com/code/3335a3fa9edb5a3b8d7e73fd85d4bad806e5ac92

add php function to json array before encoding

$selected_offer = $_POST['selected_offer'];
$get_categories = $db->query("SELECT oc_id, oc_name FROM object_category WHERE oc_relate = '".$selected_offer."'");
$json = array();
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$json[] = $get_rows;
}
echo json_encode($json);
return;
I toke this code from someone else and since I am not familiar with json I am asking here at stackoverflow how can add a function to the oc_name attribute before the json encodes it and still return the same struckture as it is now, like for example:
language($get_rows['oc_name'])
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$get_rows['oc_name'] = language($get_rows['oc_name']);
$json[] = $get_rows;
}
You can apply your function on the mentioned field before you add the row in your $json array
$json = array();
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$get_rows['oc_name']=language($get_rows['oc_name']);
$json[] = $get_rows;
}

How can I get element using xpath?

I'm trying to get some data from a HTML
$xdata = simplexml_import_dom($doc);
$datas = $xdata->xpath("//*[#class='proglist']");
$aData = array();
foreach($datas as $data)
{
$rightdatas = $data->xpath("*[#class='progright']");
$rt = $rightdatas[0];
print_r($rt);
$content = $rt->xpath("*[#class='progrighthead']");
print_r($content );
}
If I'm printing out the content of the $rt than the progrighthead class is there, but the $content variable is empty. Why?
Why do I receiving the same result for the following syntax?
$xdata = simplexml_import_dom($doc);
$datas = $xdata->xpath("//*[#class='proglist']");
$aData = array();
foreach($datas as $data)
{
$rightdatas = $data->xpath("*[#class='progright']");
$rt = $rightdatas[0];
print_r($rt);
$content = $rt->xpath("*[#class='progrighthead']");
}
and
$datas = $xdata->xpath("//*[#class='progrighthead']");
progrighthead is not a child of progright, but a descendant. Use
$rt->xpath(".//*[#class='progrighthead']");
Putting // at the beginning means searching from the root, not from the current element.

Categories