I am using a Mailgun Webhook to track events (delivered, opened, etc). I successfully redirected the event to a url that has a php file that looks like this:
<?php
$postdata = file_get_contents("php://input");
$postdata_encoded = json_encode($_POST['message-headers']);
When I echo the output I am getting the following:
[[\"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 deliver webhook\"], [\"From\", \"Bob \"], [\"To\", \"Alice \"], [\"Message-Id\", \"<20130503182626.18666.16540#mail.example.com>\"], [\"X-Mailgun-Variables\", \"{\\"my_var_1\\": \\"Mailgun Variable #1\\", \\"my-var-2\\": \\"awesome\\"}\"], [\"Date\", \"Fri, 03 May 2013 18:26:27 +0000\"], [\"Sender\", \"bob#mail.example.com\"]]
Question: How can I transform this output to a proper json format that I will be able to pass to my database? I tried something like this:
$output = array();
foreach ($postdata_encoded as $key=>$value) {
$output[$key] = $value;
}
var_dump($output);
but this returns:
Response: array(0) { }
Any idea? Many thanks
Related
I am able to send JSONObject data from my application to server with PHP. I am also able to read the data. But now I want to send the data with a USER ID and type of data in the first two sentences. I am able to send this data from my application.
But I am not experienced with working on PHP and I dont know how to split this data after reading USER id and the type I have received and to store the rest of data separately ( and should be stored as json data with USER ID as filename).
Currently I am using the following to just save the
<?php
$content = file_get_contents('php://input');
$data = json_decode($content, true);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
if(!is_array($data)){
throw new Exception('Received content contained invalid JSON!');
}
echo "Data Received";
?>
This is the json data format,
[{ "increment_id": "1", "uuid": "43c87b6e-4fd5-4f1b-9bba-3e512eb4787a", "xValue": "39.0", "yValue": "72.0", "inputTime": "Thu Mar 08 15:38:58" }]
I also want to attach user id with it, which I am able to attach and send it to server, but I cannot use json decode now as the format changes to re encode if I give a userid with it in the first sentence . So after attaching userid and type the data looks like this
UserID Type [{ "increment_id": "1", "uuid": "43c87b6e-4fd5-4f1b-9bba-3e512eb4787a", "xValue": "39.0", "yValue": "72.0", "inputTime": "Thu Mar 08 15:38:58" }]
What sentences? Send it where? Its far from clear what you are asking.
I dont know how to split this data
We don't either. What do you mean by split? That implies there's going to more than one data item - where do you want to split it? What do you want to do with the 2 parts?
should be stored as json data with USER ID as filename
It is very unlikely that it should be stored where you are currently putting it - particularly when you are applying no validation to the data you saved.
Consider (and note the differences with your script):
<?php
define("DEST_DIR", "/not/in/your/document/root/");
$content = file_get_contents('php://input');
$data = json_decode($content, true);
if (isset($data['USER'])) {
$filename=basename($data['USER']);
$filename="data_" . array_shift(explode('.', $filename) . 'json';
file_put_contents(DEST_DIR . $filename);
print json_encode(array('result'=>'success'));
} else {
header("Bad Request", true, 400);
print json_encode(array('result'=>'bad input data');
}
Am quite frustrated with this and could use some savvy minds.
Am building a relatively simple API.
Using PHP have created the stdClass()'s and json_encode.
On the host server the data echos perfectly.
On the client side am getting a persistent foreach invalid argument error.
$thefez= new stdClass();
$thefez->muid=$id;
$thefez->bandname=$bandname;
$thefez->core=new stdClass();
$thefez->core->joined=$since;
$thefez->core->bandbio=$bio;
$thefez->core->genre=$genre;
$thefez->core->subgenre=$subgenre;
echo json_encode($thefez);
The Result (Host)
{"muid":"IM5LGM02MFS8RJLKGY9W","bandname":"Marbles For Zen","core":
{"joined":"Sun 01 March 2015","bandbio":"Zen And Marbles","genre":"Rhythm Blues",
"subgenre":"Dixie Rhythm"}}
{"muid":"IMA3YNBKZQDNR9RBCSRI","bandname":"Frankie Storm","core":
{"joined":"Sat 21 February 2015","bandbio":"Just registered. Bio coming soon.","genre":"Popular","subgenre":""}}
ISSUE:
Using json_decode and foreach simply want to echo the items in the array.
json_decode(file_get_contents('http://api.mutrs.me/?artists'), TRUE);
foreach($result as $item){
$item->muid;
}
Host:
Checked json_last_error it returns 0
Checked json_last_error_msg it returns No Error
Client:
Checked json_last_error it returns 4
Checked json_last_error_msg it returns Syntax Error
jsondecode converts to array not an standard class object
try this
first $result = json_decode($object , true);
then for your item
$varname = $item['muid'];
Test this compared to Your Code:
<?php
$data = '{"muid":"IM5LGM02MFS8RJLKGY9W","bandname":"Marbles For Zen","core":{"joined":"Sun 01 March 2015","bandbio":"Zen And Marbles","genre":"Rhythm Blues","subgenre":"Dixie Rhythm"}}';
var_dump(json_decode($data , true));
?>
I'm making a Wordpress-plugin in which an administrator can add events. Visitors can see a calendar (fullcalendar) where they should see events. However, it does not read the json string which stores all the information. The string looks okay: [{"title":"Evenement01","start":"2013-11-15"},{"title":"Testevenemn12","start":"2013-11-22"}].
Below my json-feed.php code:
<?php
global $wpdb;
$rst_events_array = array();
$rst_get_events = $wpdb->get_results("
SELECT *
FROM wp_rst_events
");
foreach ($rst_get_events as $val){
$rst_events_array [] = array(
'title' => $val->rst_event_name,
'start' => $val->rst_event_date
);
}
echo json_encode($rst_events_array);
?>
And here my jQuery:
jQuery('#rst-calendar').fullCalendar({
events: 'json-feed.php'
});
Thanks in advance
I had the same issue with Wordpress and needed to add;
header("Content-Type: application/json; charset=UTF-8");
echo event::jsonCalendarEvent($id);
exit;
JSON is very particular and any characters after your echo will kill it on the client side.
You should use date/time format as specified in documentation:
The date/time an event begins. When specifying Event Objects for
events or eventSources, you may specify a string in IETF format (ex:
"Wed, 18 Oct 2009 13:00:00 EST"), a string in ISO8601 format (ex:
"2009-11-05T13:15:30Z") or a UNIX timestamp.
So, in your case:
events: [
{
"title":"Evenement01",
"start":"2013-11-15T13:15:30Z"
},
{
"title":"Testevenemn12",
"start":"2013-11-22T13:15:30Z"
}
]
Have a look here.
If you want the event lasts all day, you should set the allDay properties to true.
So this is where to view my json file: http://alyssayango.x10.mx/
this is my php file for that:
<?php
include('connectdb.php');
$sql = "SELECT * FROM tblmovies ORDER BY _id";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$set = array();
while($row1 = mysql_fetch_assoc($result)) {
$set[] = $row1;
}
echo json_encode($set);
and the output is:
[{"_id":"3","movie_name":"Despicable Me 2","movie_cinema_number":"CINEMA 1","movie_length":"1hr. 40mins.","movie_type":"GP","movie_schedules":"12:10 PM | 02:25 PM | 04:40 PM","movie_image_url":"http:\/\/i39.tinypic.com\/szizo4.jpg"},{"_id":"4","movie_name":"White House Down","movie_cinema_number":"CINEMA 2","movie_length":"2 hrs. 10 mins.","movie_type":"PG-13","movie_schedules":"12:30 PM | 03:20 PM | 06:10 PM","movie_image_url":"http:\/\/i39.tinypic.com\/vp9n9j.jpg"},{"_id":"5","movie_name":"My Lady Boss","movie_cinema_number":"CINEMA 3","movie_length":"1hr. 50 mins.","movie_type":"PG-13","movie_schedules":"01:00 PM | 03:30 PM | 06:00 PM","movie_image_url":"http:\/\/i44.tinypic.com\/2qlv08z.jpg"},{"_id":"6","movie_name":"Four Sisters And A Wedding","movie_cinema_number":"CINEMA 4","movie_length":"2 hrs. 5 mins. ","movie_type":"PG-13","movie_schedules":"12:30 PM | 03:10 PM | 05:50 PM","movie_image_url":"http:\/\/i44.tinypic.com\/9iv0d1.jpg"}]
what seems to be wrong that I do in here? URL is displayed as: http:\ /\ /i44.tinypic.com\ /9iv0d1.jpg where it should be http://i44.tinypic.com/9iv0d1.jpg
The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.
If you create an API that should be:
$array = array("title" => "TEST", "username" => "test"); // Creating a array
echo json_encode($array); // Printing json
Client want to request and get response:
$json = file_get_contents('http://www.example.com/test/films.json'); // Your url
$array = json_decode($json); // Your first array its here!
More: http://en.wikipedia.org/wiki/JSON
Warning: You can't edit or tidy your json response! It is good!
The problem does not exists, actually.
What you're doing wrong is that you're using a piece of your JSON string without decoding it beforehand. Just use json_decode(..) if you're within PHP or the equivalent javascript function to decode JSON.
Once you did that, you'll have an object / an array which contains the data in the correct form.
I am trying to use an API that returns the following structure
<TwilioResponse>
<Call>
<Sid>CAe1644a7eed5088b159577c5802d8be38</Sid>
<DateCreated>Tue, 10 Aug 2010 08:02:17 +0000</DateCreated>
<DateUpdated>Tue, 10 Aug 2010 08:02:47 +0000</DateUpdated>
<ParentCallSid/>
<AccountSid>AC5ef872f6da5a21de157d80997a64bd33</AccountSid>
<To>+14153855708</To>
<From>+14158141819</From>
<PhoneNumberSid></PhoneNumberSid>
<Status>completed</Status>
<StartTime>Tue, 10 Aug 2010 08:02:31 +0000</StartTime>
<EndTime>Tue, 10 Aug 2010 08:02:47 +0000</EndTime>
<Duration>16</Duration>
<Price>-0.03000</Price>
<Direction>outbound-api</Direction>
</Call>
</TwilioResponse>
I can get to the XML data by using CURL which works fine like this:
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $base_url."/Accounts/{$accountSid}/Calls");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
curl_close($handle);
however once I get the data back as XML I try and put it into a simpleXML element and return it back to the page that called this function as follows:
$xml = new SimpleXmlElement($response);
if($xml)
{
return $xml;
}
else
{
return false;
}
When I return the XML to the page that called the function, I can see a whole lot of simpleXMLElement Objects if I do a print_r() but when I try and do a foreach($xml->TwilioResponse->call as $call) I get nothing and it does not seem like I can actually drill into the data at all.
Can someone help me and point out where I am going wrong with this? It has been driving me absolutely crazy for the past couple of hours.
THANKS!
It looks like there are two problems with $xml->TwilioResponse->call.
$xml contains the TwilioResponse element (the "document element"), $xml->TwilioResponse is incorrect.
(XML and) SimpleXML element names are case-sensitive, call should be Call.
Give $xml->Call a spin.