extracting field from twitter feed using json_decode - php

I am trying to grab my twitter feed using the following code:
// Make the request and get the response into the $json variable
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
// It's json, so decode it into an array
$result = json_decode($json);
// Access the profile_image_url element in the array
echo $result->created_at;
?>
I get the result of:
Thu Oct 25 18:40:50 +0000 2012
If I try to get the text with:
echo $result->text;
I get this error:
Notice: Undefined property: stdClass::$text in /Library/WebServer/Documents/include/twitter_noformat/items.php on line 35
A partial var_dump of my data format includes this:
{"created_at":"Thu Aug 01 16:12:18 +0000 2013",
"id":362969042497175553,
"id_str":"362969042497175553",
"text":"A warm welcome to our new international students from China, Hong Kong and Germany! http:\/\/t.co\/GLvt3GynJV",
"source":"web",
"truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":
My question is:
created_at gives me a value. id gives me a value. Why doesn't text? I know nothing about JSON btw. I'm not a very advanced programmer, but the pattern looks the same to me.
Edit: Well I found a cool snippet that converted my twitter array to something more readable. The function goes like this:
// It's json, so decode it into an array
$result = json_decode($json);
// Access the profile_image_url element in the array
$pretty = function($v='',$c=" ",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'<NULL>':"<strong>$v</strong>");}return$r;};
echo $pretty($result);
The results now look like this:
statuses_count: 583
lang: en
status:
created_at: Thu Aug 01 21:10:10 +0000 2013
id: 363044004444651522
id_str: 363044004444651522
text: #CalStateEastBay AD Sara Lillevand Judd '86 honored for her work as an athletic adminstrator. http://t.co/WzOqjIDrBw
This is strange because that makes text look like it's part of an object?
I have determined that twitter kicks back an array of objects. Those objects can have a lot of items(?) As I mentioned previously though I can echo $result->created_at; but not text. They are both at the same level of the array.
thanks in advance for your help,
Donovan

Alright here was my solution after a day of research:
$result = json_decode( $json );
echo "Text:" . $result->status->text . "<br />";
Text was a child(?) of status. I could echo created_at because it was used at two levels of the array, which I hadn't seen before. Text was inside the status object I guess.
created_at: Thu Oct 25 18:40:50 +0000 2012
favourites_count: 1
utc_offset: -25200
time_zone: Pacific Time (US & Canada)
geo_enabled: 1
verified:
statuses_count: 583
lang: en
status:
created_at: Thu Aug 01 21:10:10 +0000 2013
id: 363044004444651522
id_str: 363044004444651522
text: #CalStateEastBay AD Sara Lillevand Judd '86 honored for her work as an athletic adminstrator. http://t.co/WzOqjIDrBw

Related

PHP: Need to find certain data from a string

$string = "Response 22: 404 (8345ms), headers: Accept-Ranges=bytes,
Cache-Control=no-cache, no-store, private, Connection=close,
Content-Encoding=gzip, Content-Language=it-it, Content-Length=1674,
Content-Location=index.html.it-it, Content-Type=text/html;
charset=utf-8, Date=Wed, 24 Sep 2014 19:01:30 GMT,
ETag='eb1-50331586750c0;503ac178f62dd', Last-Modified=Tue, 16 Sep 2014
16:35:55 GMT, Server=Apache,
Strict-Transport-Security=max-age=31536000; includeSubDomains,
TCN=choice, Vary=negotiate,accept,accept-language,Accept-Encoding,
X-Frame-Options=SAMEORIGIN, X-UA-Compatible=IE=Edge";
Here I want to grab response number(=> 22), response code(=> 404) and its milli seconds(=> 8345ms).
I think I have to use regex, but I am new to that. Can you please give any suggestions?
Response\s*(\d+):\s*(\d+)\s*\((\S+)?\)
Try this.Get the three groups.See demo.
http://regex101.com/r/qC9cH4/3

How to print a string in an object in PHP

I get the following object in response to a call in PHP:
Transaction[id=g855fm, type=sale, amount=100.00,
status=processed, createdAt=Tuesday, 24-Jun-14 19:17:58
UTC]
I am able to echo id, amount, status etc. but createdAt does not print. Perhaps because it has a comma (,) in it? I want to convert the sate from string format to mm/dd/yyyy but I can not format it to mm/dd/yyyy because I am not able to get createdAt.
echo $object->createdAt; prints nothing.
echo $object->id; prints g855fm.
echo $object->status; prints processed.
This is the whole object:
Braintree_Subscription[
addOns=,
balance=0.00,
billingDayOfMonth=24,
billingPeriodEndDate=Wednesday, 23-Jul-14 00:00:00 MDT,
billingPeriodStartDate=Tuesday, 24-Jun-14 00:00:00 MDT,
currentBillingCycle=1,
daysPastDue=,
discounts=,
failureCount=0,
firstBillingDate=Tuesday, 24-Jun-14 00:00:00 MDT,
id=6q6qg2,
merchantAccountId=XXXX,
neverExpires=1,
nextBillAmount=100.00,
nextBillingPeriodAmount=100.00,
nextBillingDate=Thursday, 24-Jul-14 00:00:00 MDT,
numberOfBillingCycles=,
paidThroughDate=Wednesday, 23-Jul-14 00:00:00 MDT,
paymentMethodToken=3mzhf6,
planId=XXXX,
price=100.00,
status=Active,
trialDuration=,
trialDurationUnit=day,
trialPeriod=,
descriptor=Braintree_Descriptor[
name=, phone=
],
transactions=
0=Braintree_Transaction[
id=h2v7qm,
type=sale,
amount=100.00,
status=submitted_for_settlement,
createdAt=Wednesday, 25-Jun-14 03:53:07 UTC,
creditCardDetails=Braintree_Transaction_CreditCardDetails[
token=3mzhf6,
bin=411111,
last4=1111,
cardType=Visa,
expirationMonth=06,
expirationYear=2014,
customerLocation=US,
cardholderName=,
imageUrl=https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox&merchant_id=XXXX,
prepaid=Unknown,
healthcare=Unknown,
debit=Unknown,
durbinRegulated=Unknown,
commercial=Unknown,
payroll=Unknown,
issuingBank=Unknown,
countryOfIssuance=Unknown,
productId=Unknown,
venmoSdk=,
expirationDate=06/2014,
maskedNumber=411111******1111
],
customerDetails=Braintree_Transaction_CustomerDetails[
id=59273593,
firstName=XXXX,
lastName=,
company=,
email=XXXX,
website=,
phone=XXXX,
fax=
]
]
]
I am accessing it like: $object->transactions[0]->createdAt
Update:
echo $object->transactions[0]->createdAt->format('r'); is: Wed, 25 Jun 2014 04:07:42 +0000
I will now try to use it now for date formatting. I want it in date(dd/mm/yyyy) format. Any idea how to do that?
I think that you have turned off display errors. When trying to echo DateTime object you are receiving silent fatal error.
Try echo $object->transactions[0]->createdAt->format('d/m/Y');
You should call print the object like this
<?php print_r($object); ?>

Easy- Json and PHP decode

I'm working with an API from underground weather. I'm trying to put some values into my website on localhost. I include a lot of values without problem. Like:
Temperature: 30°F
Wind: Fast
Here is the json of those values:
"current_observation": {
"image": {
"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title":"Weather Underground",
"link":"http://www.wunderground.com"
},
"display_location": {
"full":"Buenos Aires, Argentina",
"city":"Buenos Aires",
"state":"",
"state_name":"Argentina",
"country":"AG",
"country_iso3166":"AR",
"zip":"00000",
"magic":"1",
"wmo":"87582",
"latitude":"-34.56999969",
"longitude":"-58.41999817",
"elevation":"6.00000000"
},
"observation_location": {
"full":"Palermo, Buenos Aires, Ciudad Autónoma de Buenos Aires",
"city":"Palermo, Buenos Aires",
"state":"Ciudad Autónoma de Buenos Aires",
"country":"Argentina",
"country_iso3166":"AR",
"latitude":"-34.595318",
"longitude":"-58.419781",
"elevation":"124 ft"
},
"estimated": {
},
"station_id":"IBUENOSA157",
"observation_time":"Last Updated on April 26, 7:52 PM ART",
"observation_time_rfc822":"Sat, 26 Apr 2014 19:52:51 -0300",
"observation_epoch":"1398552771",
"local_time_rfc822":"Sat, 26 Apr 2014 19:52:52 -0300",
"local_epoch":"1398552772",
"local_tz_short":"ART",
"local_tz_long":"America/Buenos_Aires",
"local_tz_offset":"-0300",
"weather":"Clear",
"temperature_string":"65.8 F (18.8 C)",
"temp_f":65.8,
"temp_c":18.8,
"relative_humidity":"63%",
and in the index php file:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/f84c5a4cd54b3216/geolookup/alerts/astronomy/almanac/conditions/forecast/hourly/q/autoip.json");
$parsed_json = json_decode($json_string);
$temp_c = $parsed_json->{'current_observation'}->{'temp_c'};
echo "{$'temp_c'};
That displays the temperature. The temperature in the json code is in: Current_observation and then the value temp_c.
The problem is that I want to echo the forecast, and the forecast is in a different location than the temp_c.
For example. I want to echo the current conditions, that is here:
The problem is, that is in:
{'forecast'}->{'simpleforecast'}->{'forecastday'} and then there is a zero for the current day, a 1 for the next day, a 2 for the following day, and a 3 for the next to the next day.
When I try to do that in php:
{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'0'}->{'conditions'};
It does not show anything. How I can go into a value json when in the array there is a 0?
PD: for 0, there is one condition, for 1 (that is next day) there is other condition, and like that the others day. Thanks
For me it just works fine, I just tested your code, I just modified it a little bit:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/f84c5a4cd54b3216/geolookup/alerts/astronomy/almanac/conditions/forecast/hourly/q/autoip.json");
$parsed_json = json_decode($json_string, true);
$desired_forecast = $parsed_json['forecast']['simpleforecast']['forecastday'][0]['conditions'];
echo '<pre>';
print_r($desired_forecast); // Thunderstorm
echo '</pre>';
It is accessible.
You were really close but {'0'} means there is an object with the key 0, while you really wanted to access the first index of forecastday
var_dump($parsed_json->{'forecast'}->{'simpleforecast'}->{'forecastday'}[0]->conditions);

fullCalendar "events: 'somepage.php'" JSON Results not displaying

I am trying to get the events for my fullCalendar implementation with the "events (as a JSON feed)" built in feature.
...
event: 'calendarFill.php',
...
The php file returns the following JSON data:
[{"id":"40","title":"test four","services":"Reflexology (40), foot-soak","start":"Tue Mar 26 2013 13:00:00","end":"Tue Mar 26 2013 13:40:00","color":"#e56b15","customerId":"21","phone":"555-0404","email":"test4","notes":"test two of update. this sentence added at update.","seat":"Side Couch 9","vip":"yes","confirmed":"yes","knows_policies":"yes","customer_here":"0","allDay":"false"},{"id":"41","title":"test four","services":"Foot-Soak, ","start":"Wed Mar 27 2013 19:00:00","end":"Wed Mar 27 2013 19:15:00","color":"#e56b15","customerId":"21","phone":"555-0404","email":"test4","notes":"test of addslashes. what's going to happen?","seat":"Front Chair 2","vip":"yes","confirmed":"yes","knows_policies":"yes","customer_here":"0","allDay":"false"}]
The above does not work - the events are not displayed on the calendar. I've cut and pasted the code directory in my Javascript code:
events: {"id":"40","title":"test four","services":"Reflexology (40), foot-soak","start":"Tue Mar 26 2013 13:00:00","end":"Tue Mar 26 2013 13:40:00","color":"#e56b15","customerId":"21","phone":"555-0404","email":"test4","notes":"test two of update. this sentence added at update.","seat":"Side Couch 9","vip":"yes","confirmed":"yes","knows_policies":"yes","customer_here":"0","allDay":"false"},{"id":"41","title":"test four","services":"Foot-Soak, ","start":"Wed Mar 27 2013 19:00:00","end":"Wed Mar 27 2013 19:15:00","color":"#e56b15","customerId":"21","phone":"555-0404","email":"test4","notes":"test of addslashes. what's going to happen?","seat":"Front Chair 2","vip":"yes","confirmed":"yes","knows_policies":"yes","customer_here":"0","allDay":"false"}],
And, it does not display. But, if I edit the above to remove all the quotes that are not surrounding text values (as below), IT WORKS.
events: [{id:40,title:"test four",services:"Reflexology (40), foot-soak",start:"Tue Mar 26 2013 13:00:00",end:"Tue Mar 26 2013 13:40:00",color:"#e56b15",customerId:21,phone:"555-0404",email:"test4",notes:"test two of update. this sentence added at update.",seat:"Side Couch 9",vip:"yes",confirmed:"yes",knows_policies:"yes",customer_here:0,allDay:false},{id:41,title:"test four",services:"Foot-Soak, ",start:"Wed Mar 27 2013 19:00:00",end:"Wed Mar 27 2013 19:15:00",color:"#e56b15",customerId:21,phone:"555-0404",email:"test4",notes:"test of addslashes. what's going to happen?",seat:"Front Chair 2",vip:"yes",confirmed:"yes",knows_policies:"yes",customer_here:0,allDay:false}],
I am using the documentation at this link: http://arshaw.com/fullcalendar/docs/event_data/events_json_feed/
What am I doing wrong? Should I remove the 'json_encode' from my php and just return a string formatted like the above? I'd like to do it the 'right' way and not some work-around.
Added the php as requested:
// for connection to db
include("../includes/config.php");
include("../includes/mysql_functions.php");
// connection with db
$linkID = db_connect();
$returnValue = array();
$getEventData = mysql_query("SELECT apt_num, services, apt_date_start, apt_date_end, therapist, customer_num, notes, seat, confirmed, knows_policies, here FROM appointments", $linkID);
if ($getEventData != FALSE && mysql_num_rows($getEventData) > 0)
{
while ($theEventData = mysql_fetch_array($getEventData))
{
$getCustomerString = "SELECT first_name, middle_name, last_name, phone, email, vip FROM customer WHERE customer_num = ".$theEventData['customer_num'];
$getCustomerData = mysql_query($getCustomerString, $linkID);
if ($getCustomerData != FALSE && mysql_num_rows($getCustomerData) > 0)
{
while($theCustomerData = mysql_fetch_array($getCustomerData))
{
$customerName = $theCustomerData['first_name']." ".$theCustomerData['middle_name']." ".$theCustomerData['last_name'];
$customerPhone = $theCustomerData['phone'];
$customerEmail = $theCustomerData['email'];
$customerVip = $theCustomerData['vip'];
}
}
else
{
$customerName = "error";
$customerPhone = "error";
$customerEmail = "error";
$customerVip = "error";
}
$rowArray['id'] = $theEventData['apt_num'];
$rowArray['title'] = $customerName;
$rowArray['services'] = $theEventData['services'];
$rowArray['start'] = date("D", $theEventData['apt_date_start'])." ".date("M", $theEventData['apt_date_start'])." ".date("d", $theEventData['apt_date_start'])." ".date("Y", $theEventData['apt_date_start'])." ".date("H", $theEventData['apt_date_start']).":".date("i", $theEventData['apt_date_start']).":".date("s", $theEventData['apt_date_start']);
$rowArray['end'] = date("D", $theEventData['apt_date_end'])." ".date("M", $theEventData['apt_date_end'])." ".date("d", $theEventData['apt_date_end'])." ".date("Y", $theEventData['apt_date_end'])." ".date("H", $theEventData['apt_date_end']).":".date("i", $theEventData['apt_date_end']).":".date("s", $theEventData['apt_date_end']);
$rowArray['color'] = $theEventData['therapist'];
$rowArray['customerId'] = $theEventData['customer_num'];
$rowArray['phone'] = $customerPhone;
$rowArray['email'] = $customerEmail;
$rowArray['notes'] = $theEventData['notes'];
$rowArray['seat'] = $theEventData['seat'];
$rowArray['vip'] = $customerVip;
$rowArray['confirmed'] = $theEventData['confirmed'];
$rowArray['knows_policies'] = $theEventData['knows_policies'];
$rowArray['customer_here'] = $theEventData['here'];
$rowArray['allDay'] = "false";
array_push($returnValue, $rowArray);
}
}
else
{
$returnValue[0] = "error";
}
print json_encode($returnValue);
Markus Vetter (from Google+) found the problem. In the original code returned from my php file there is an "'" that causes an issue. I needed to 'addslashes' to my php before returning it to the jQuery/Javascript. Once that was done, the jQuery / fullCalendar code was able to render my events as expected.
A second pair of eyes does wonders! Thank you Markus Vetter!
The original code returned:
[{"id":"40","title":"test four","services":"Reflexology (40), foot-soak","start":"Tue Mar 26 2013 13:00:00","end":"Tue Mar 26 2013 13:40:00","color":"#e56b15","customerId":"21","phone":"555-0404","email":"test4","notes":"test two of update. this sentence added at update.","seat":"Side Couch 9","vip":"yes","confirmed":"yes","knows_policies":"yes","customer_here":"0","allDay":"false"},{"id":"41","title":"test four","services":"Foot-Soak, ","start":"Wed Mar 27 2013 19:00:00","end":"Wed Mar 27 2013 19:15:00","color":"#e56b15","customerId":"21","phone":"555-0404","email":"test4","notes":"test of addslashes. what's going to happen?","seat":"Front Chair 2","vip":"yes","confirmed":"yes","knows_policies":"yes","customer_here":"0","allDay":"false"}]
After using 'addslashes' in my php for all text fields:
[{"id":"40","title":"test four","services":"Reflexology (40), foot-soak","start":"Tue Mar 26 2013 13:00:00","end":"Tue Mar 26 2013 13:40:00","color":"#e56b15","customerId":"21","phone":"555-0404","email":"test4","notes":"test two of update. this sentence added at update.","seat":"Side Couch 9","vip":"yes","confirmed":"yes","knows_policies":"yes","customer_here":"0","allDay":"false"},{"id":"41","title":"test four","services":"Foot-Soak, ","start":"Wed Mar 27 2013 19:00:00","end":"Wed Mar 27 2013 19:15:00","color":"#e56b15","customerId":"21","phone":"555-0404","email":"test4","notes":"test of addslashes. what\'s going to happen?","seat":"Front Chair 2","vip":"yes","confirmed":"yes","knows_policies":"yes","customer_here":"0","allDay":"false"}]
Actually solved this time! In my php file, the last value added to the $rowArray is: $rowArray['allDay'] = "false". Instead of being a text value, it needs to be the actual boolean value. This "$rowArray['allDay'] = false" fixed the problem.
I had the same issue and it was a formatting thing for me as well.
This is how my json is returning now and it is finally working.
[{"title":"Coke Trade Show","start":"2014-12-03"},{"title":"Michigan Show","start":"2014-12-04"}]
Definitely a good idea to paste your json return straight into the JS to make sure it is working.

List files in dropbox folder

Im having problems with the dropbox API.
When i try to get the metadata for my folder, i get the data output like this:
{"hash":"10f86b5b7c9c9276501f67a71ecd41c9","thumb_exists":false,"bytes":0,"path":"\/","is_dir":true,"size":"0 bytes","root":"app_folder","contents":[{"revision":7,"rev":"7069e0896","thumb_exists":true,"bytes":19749,"modified":"Tue, 20 Mar 2012 05:06:43 +0000","client_mtime":"Mon, 26 Sep 2011 11:50:43 +0000","path":"\/1_sml.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"19.3 KB"},{"revision":6,"rev":"6069e0896","thumb_exists":true,"bytes":15797,"modified":"Tue, 20 Mar 2012 05:06:43 +0000","client_mtime":"Mon, 26 Sep 2011 11:51:09 +0000","path":"\/2_sml.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"15.4 KB"},{"revision":5,"rev":"5069e0896","thumb_exists":true,"bytes":13349,"modified":"Tue, 20 Mar 2012 05:06:43 +0000","client_mtime":"Mon, 26 Sep 2011 11:51:26 +0000","path":"\/3_sml.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"13 KB"},{"revision":4,"rev":"4069e0896","thumb_exists":true,"bytes":8838,"modified":"Tue, 20 Mar 2012 05:06:43 +0000","client_mtime":"Mon, 26 Sep 2011 11:51:46 +0000","path":"\/4_sml.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"8.6 KB"},{"revision":3,"rev":"3069e0896","thumb_exists":true,"bytes":99646,"modified":"Tue, 20 Mar 2012 04:57:58 +0000","client_mtime":"Tue, 20 Sep 2011 14:14:26 +0000","path":"\/bg.jpg","is_dir":false,"icon":"page_white_picture","root":"dropbox","mime_type":"image\/jpeg","size":"97.3 KB"}],"icon":"folder"}
My problem is that i would like get the output for each the image/file name only.. But i can find the right way to do it.. i through i could do it this way:
$info = json_encode($dropbox->getMetaData(''));
foreach($info->contents->path as $file){
echo $file;
}
But i get this error:
Warning: Invalid argument supplied for foreach() in /home/djrasmusp/rasmusp.com/db/index.php on line 16
But is there anyone that can give me a helping hand with my problem?
Try json_decode instead of json_encode (and maybe use second parameter to produce associated array instead of stdClass).
I had the same problem, here is my solution:
$metaData = $dropbox->metaData($path);
foreach($metaData['body']->contents as $file){
$f = str_replace("/", "", $file->path);
echo "<li>$f</li>";
}
tested by me :)
require_once('bootstrap.php');
$metaData = $dropbox->metaData();
foreach($metaData['body']->contents as $file)
{
echo "<pre>";
echo $file->path;
}

Categories