How to print a string in an object in PHP - 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); ?>

Related

Unable to get date/time from XML - Strange value in source

I'm just starting with php, but this is a thing I can't figure out.
I browsed the internet / stack / other forums, but for now I don't have any clue.
The date format is something I can't understand / recognize at all:
<datum>1491976626</datum>
<datum>1491894573</datum>
<datum>1491734853</datum>
<datum>1491680837</datum>
<datum>1491671357</datum>
Here's the link to the XML: Link
When you check the 'datum' node, you'll see it.
As an example (compared to the output on this site)
Value: 1491734853
= Date: 09-04-2017
Value: 1491671357
= Date: 08-04-2017
Value: 1491463926
= Date: 06-04-2017
Anyone of you guys / guru's have an idea how to get this working? Is there a default (sort of) algoritm for this or something I don't know of?
Thank you very much for thinking with me :)
I think this should do the job, but I'm unable to get it to show..
This is the PHP code I have so far:
<?php
foreach ($xml->beoordelingen->beoordeling as $beoordelingenoverzicht) {
echo "<div class='containerbeoordeling'><div class='hoofd'>";
foreach($beoordelingenoverzicht->voornaam as $label => $voornaam) {
echo "<div class='naam'><span id='label'>Naam</span><span id='voornaam'>{$voornaam}</span>"; }
foreach($beoordelingenoverzicht->achternaam as $label => $achternaam) {
echo "<span id='achternaam'> {$achternaam}</span></div>";
}
foreach($beoordelingenoverzicht->datum as $label => $datum) {
$datumnew = date('Y-m-d h:i:s',$datum);
echo "<div class='datum'><span id='label'>{$label}</span><span id='datum'>{$datumnew}</span></div></div>";
}
foreach($beoordelingenoverzicht->beschrijving as $label => $beschrijving) {
echo "<div class='beschrijving'>{$beschrijving}</div>";
}
echo "</div>";
}
?>
I wouldn't be surprised if I implemented it totally wrong :D
It suppose it's just a Unix timestamp, one of the most ubiquitous date formats in computer science. Many PHP date functions support it natively, e.g. date():
var_dump(date('r', 1491734853));
// string(31) "Sun, 09 Apr 2017 12:47:33 +0200"
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().

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

extracting field from twitter feed using json_decode

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

Trouble using PHP to parse an XML document with identical tags

Here is a snippet from yahoo Weather showing the identical tags
<yweather:forecast day="Mon" date="16 Jan 2012" low="-1" high="6" text="Clear" code="31"/>
<yweather:forecast day="Tue" date="17 Jan 2012" low="3" high="7" text="Mostly Sunny" code="34"/>
To access the day in the first tag I use the following function:
function get_forecast_day(SimpleXMLElement $xml) {
// Pull forecast day
$forecast['day'] = $xml->channel->item->children('yweather', TRUE)->forecast->attributes()->day;
echo $forecast['day'] . ", ";
return $day;
}
Any ideas how I can access the day in the second tag. Obviously searching for the value "Tue" is no good as these values will change daily.
Thanks in advance.
->forecast can be used as array, so go for second element with index 1:
$xml->channel->item->children('yweather', TRUE)->forecast[1]->attributes()->day

preg_match for mysql date format

im trying to validate a date to see if it matchs the mysql format
this is the code
$match = "/^\d{4}-\d{2}-\d{2} [0-2][0-3]:[0-5][0-9]:[0-5][0-9]$/";
$s = $this->input->post("report_start"). " " . $this->input->post("report_start_time").":00";
$e = $this->input->post("report_end"). " " . $this->input->post("report_end_time").":59";
if($this->input->post("action") != "")
{
echo trim($s). " => " . preg_match($match, trim($s));
echo "<br>";
echo trim($e). " => " . preg_match($match, trim($e));
}
the date format goes into $s and $e are
$s = 2011-03-01 00:00:00
$e = 2011-03-01 23:59:59
and they both return false (0).
i tested the pattern on http://www.spaweditor.com/scripts/regex/index.php and it returns true (1)
http://pastebin.com/pFZSKYpj
however if i manual inter the date strings into preg_match like
preg_match($match, "2011-03-01 00:00:00")
it works.
i have no idea what im doing wrong
======================
now that i think about it, i only need to validate the houre:min part of the datetime string.
im manually adding the seconds and the date is forced by a datepicker and users cant edit it
You're making your work harder that it needs to be. In php there are many date handling functions that mean you don't have to treat dates like strings. So, rather than test that your input dates are in the correct format, just insist on the correct format:
$adate= date_create('January 6, 1983 1:30pm'); //date format that you don't want
$mysqldate= $adate->format("Y-m-d h:i:s");//date format that you do want
There are also functions to check that a date is a real date, like checkdate.
ok heres wat i did.
since im forcing the date format and the ending seconds of the time part
i just validated the hour:mini part using "/^2[0-3]|[01][0-9]:[0-5][0-9]$";
and if that returns true i put everything together end reconstructed the final datetime string
$match = "/^2[0-3]|[01][0-9]:[0-5][0-9]$/";
$s_d = $this->input->post("report_start");
$s_t = $this->input->post("report_start_time");
$e_d = $this->input->post("report_end");
$e_t = $this->input->post("report_end_time");
if($this->input->post("action") != "")
{
if(
( preg_match($match , trim($s_d." ".$s_t.":00")) )
&& ( preg_match($match , trim($e_d." ".$e_t.":59")) )
)
{
$r = $this->model_report->client_hours_logged(array($s,$e));
$data['report'] = $r;
var_dump($r);
//$this->load->view("report/client_hours_per_client",$data);
}
}
Watch out:
[0-2][0-3] is not a good regex for hour values - it will match 01, 12, 23 and others, but it will fail 04 through 09 and 14 through 19.
Better use (2[0-3]|[01][0-9]) instead.
I use this to validate a 'Y-m-d H:i:s' format date string:
match = '/^[12][0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[01]) ([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/';
You could use strtotime and date to parse and format the date properly.
Why not just simply force the date into the format you want:
$e = '2011-03-01 00:00:00';
$mysqlFormat = date('Y-m-d H:i:s', strtotime($e));
Also, there is a bit of an error in your regex [0-2][0-3]:[0-5][0-9]:[0-5][0-9] will only match the hours of 00,01,02,03,10,11,12,13,20,21,22,23 so it will never match 4am, or 3pm among others. That aside I looked over your RegEx and I don't see any problems with it matching the test cases you've offered. I would check to make sure there is not extra whitespace on either side of date string with trim().
I concur with Tim : MySQL behaves in quirks mode and always tries to go easy on DATE and DATE_TIME column types. You can omit certain parts of your input and it still will try to compensate and achieve that goal successfully to some degree... That's why, most numbers your Reg-ex considers as invalid, MySQL will accept as valid.

Categories