I have found many threads about Mailgun json response here but none answers my question
Mailgun returns this string as part of a webhook POST request:
[["Received", "by luna.mailgun.net with SMTP mgrt 8734663311733; Fri, 03 May
2013 18:26:27 +0000"], ["Content-Type", ["multipart/alternative", {"boundary":
"eb663d73ae0a4d6c9153cc0aec8b7520"}]], ["Mime-Version", "1.0"], ["Subject",
"Test bounces webhook"], ["From", "Bob <bob#domain.com.cz>"], ["To", "Alice
<alice#example.com>"], ["Message-Id", "
<20130503182626.18666.16540#domain.com>"], ["List-Unsubscribe", "
<mailto:u+na6tmy3ege4tgnldmyytqojqmfsdembyme3tmy3cha4wcndbgaydqyrgoi6wszdpovr
hi5dinfzw63tfmv4gs43uomstimdhnvqws3bomnxw2jtuhusteqjgmq6tm#example.com>"], ["X-
Mailgun-Sid", "WyIwNzI5MCIsICJhbGljZUBleGFtcGxlLmNvbSIsICI2Il0="], ["X-Mailgun-
Variables", "{"my_var_1": "Mailgun Variable #1", "my-var-2": "awesome"}"],
["Date", "Fri, 03 May 2013 18:26:27 +0000"], ["Sender", "bob#domain.com"]]
The question is, how to parse it using PHP? json_decode returns null. I need to get Subject from that string. Thanks
This is the full response I get:
[
attachment-count => 1,
code => 550,
domain => "domain.com",
error => "5.1.1 The email account that you tried to reach does not exist. Please try5.1.1 double-checking the recipient's email address for typos or5.1.1 unnecessary spaces. Learn more at5.1.1 http://support.example.com/mail/bin/answer.py",
event => "bounced",
message-headers => "[["Received", "by luna.mailgun.net with SMTP mgrt 8734663311733; Fri, 03 May 2013 18:26:27 +0000"], ["Content-Type", ["multipart/alternative", {"boundary": "eb663d73ae0a4d6c9153cc0aec8b7520"}]], ["Mime-Version", "1.0"], ["Subject", "Test bounces webhook"], ["From", "Bob <bob#domain.com>"], ["To", "Alice <alice#example.com>"], ["Message-Id", "<20130503182626.18666.16540#domain.com>"], ["List-Unsubscribe", "<mailto:u+na6tmy3ege4tgnldmyytqojqmfsdembyme3tmy3cha4wcndbgaydqyrgoi6wszdpovrhi5dinfzw63tfmv4gs43uomstimdhnvqws3bomnxw2jtuhusteqjgmq6tm#lidskasila.cz>"], ["X-Mailgun-Sid", "WyIwNzI5MCIsICJhbGljZUBleGFtcGxlLmNvbSIsICI2Il0="], ["X-Mailgun-Variables", "{"my_var_1": "Mailgun Variable #1", "my-var-2": "awesome"}"], ["Date", "Fri, 03 May 2013 18:26:27 +0000"], ["Sender", "bob#domain.com.cz"]]",
Message-Id => "<20130503182626.18666.16540#lidskasila.cz>",
recipient => "alice#example.com",
signature => "0359cb85c5b22e8de04232f74a77b94d41dc539e0c64034f6787562648bf638c",
timestamp => 1457955019,
token => "cd5808bd17b3523cbbd18426841cec0e0c897d4c325d2c9621",
X-Mailgun-Sid => "WyIwNzI5MCIsICJhbGljZUBleGFtcGxlLmNvbSIsICI2Il0="
]
The thing is that message-headers variable has the correct JSON format. As to Mailgun - order of headers preserved. So this is the code for Subject value:
$tmp = $_POST['message-headers'];
$data = json_decode($tmp);
$subject = $data[3][1];
I am using PHP to get the email from the POP3 server. However, some emails also contain the original message which I sent to them.
How do I remove the original message, so the PHP script will only get the reply message?
For example:
Email sent from A to B
A
11:08 PM (1 minute ago)
to B
how are you?
Email replied from B to A
11:08 PM (0 minutes ago)
to A
I am fine
> On Sun, Mar 8, 2015 at 11:08 PM, Ryan Ho <ryan#incube.com.hk> wrote:
> how are you?
I would like to remove those wordings "On Sun Mar 8,.... to how are you?".
Thanks.
First, you can save the email in a file, then you can remove all the lines starting with > using a regular expression.
This is because all lines from the original message start with the symbol >, including the text:
On Sun, Mar 8, ... wrote: how are you?
Here is the code doing that:
<?php
$filename="email-full.txt";
$outfile="email-noreply.txt";
$string = file_get_contents($filename);
$array = explode("\n",$string);
foreach($array as $arr) {
if(!(preg_match("/^>/",$arr))) {
$output[] = $arr;
}
}
$out = implode("\n",$output);
file_put_contents($outfile,$out);
?>
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
I have two bits of code that seem to be correct translations of one another. They unfortunately appear to return different values.
Code in Ruby:
def separate(text,boundary = nil)
# returns array of strings and arrays containing all of the parts of the email
textList = []
if !boundary #look in the email for "boundary= X"
text.scan(/(?<=boundary=).*/) do |bound|
textList = recursiveSplit(text,bound)
end
end
if boundary
textList = recursiveSplit(text,boundary)
end
puts textList.count
return textList
end
def recursiveSplit(chunk,boundary)
if chunk.is_a? String
searchString = "--" + boundary
ar = chunk.split(searchString)
return ar
elsif chunk.is_a? Array
chunk do |bit|
recursiveSplit(bit,boundary);
end
end
end
Code in PHP:
function separate($text, $boundary="none"){
#returns array of strings and arrays containing all the parts of the email
$textBlock = [];
if ($boundary == "none") {
preg_match_all('/(?<=boundary=).*/', $text, $matches);
$matches = $matches[0];
foreach ($matches as $match) {
$textList = recursiveSplit($text,$match);
}
}else {
$textList = recursiveSplit(text,boundary);
}
var_dump($textList);
return$textList;
}
function recursiveSplit($chunk,$boundary){
if (is_string($chunk)) {
$ar = preg_split("/--".$boundary."/", $chunk);
//$ar = explode($searchString, $chunk);
return $ar;
}
elseif (is_array($chunk)) {
foreach ($chunk as $bit) {
recursiveSplit($bit,$boundary);
}
}
}
var_dump($textList) shows an array of length 3, whereas textList.count => 4. What gives?
Anonymized $text example:
MIME-Version: 1.0
Received: by 10.112.170.40 with HTTP; Fri, 3 May 2013 05:08:21 -0700 (PDT)
Date: Fri, 3 May 2013 08:08:21 -0400
Delivered-To: me#gmail.com
Message-ID: <CADPp44E47syuXvP1K-aemhcU7vdSijZkfKLu-74QPWs9U9551Q#mail.gmail.com>
Subject: MiB 5/3/13 7:43AM (EST)
From: Me <me#gmail.com>
To: Someone <someone#aol.com>
Content-Type: multipart/mixed; boundary=BNDRY1
--BNDRY1
Content-Type: multipart/alternative; boundary=BNDRY2
--BNDRY2
Content-Type: text/plain; charset=ISO-8859-1
-TEXT STUFF HERE. SAYING THINGS
ABOUT CERTAIN THINGS
--BNDRY2
Content-Type: text/html; charset=ISO-8859-1
<div dir="ltr">-changed signature methods to conform more to working clinic header methods(please test/not testable in simulator)<div style>-confirmed that signature image is showing up in simulator. Awaiting further tests</div>
<div style>-Modified findings spacing/buffer. See if you like it</div></div>
--BNDRY2--
--BNDRY1
Content-Type: application/zip; name="Make it Brief.ipa.zip"
Content-Disposition: attachment; filename="Make it Brief.ipa.zip"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_hg9biuno0
<<FILE DATA>>
--BNDRY1--
Run separate(text) on example or any gmail "view original" email in order to reproduce error
BINGO ZINGO Figured it out!
Apparently, in PHP, in order to change a variable inside a loop involving that variable, you have to preface the variable with '&'
Added '&' and fixed some general recursion errors and it ran smoothly.
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.