سؤال

I have a MailGun account and I am making a PHP script that will grab attachments of emails sent to the MailGun email address I have set up.

When an email is sent to the address, MailGun sends a notification to my PHP script below with a URL to the full message content in JSON. I then go to grab that message. It works fine up until that. I get the full JSON message -- the issue is trying to work with the JSON.

Here is what I have so far for the PHP script

// Grab contents of message ( Already in JSON format (i think ? ))
$json = file_get_contents($api_url);
$json2 = json_decode($json);

foreach($json2->attachments->url AS $attach) {

    file_put_contents('test.txt', $attach, FILE_APPEND);

}

The $json variable returns the following (redacted most of the unnecessary code):

{
   "attachments":[
      {
         "url":"fullMailGunURLtoAttachment.jpg",
         "content-type":"image/jpeg",
         "name":"logo-lrg.jpg",
         "size":45465
      }
   ],
   "body-html":"<html>\r\n<head>\r\n<style><!--\r\n.hmmessage P\r\n{\r\nmargin:0px;\r\npadding:0px\r\n}\r\nbody.hmmessage\r\n{\r\nfont-size: 12pt;\r\nfont-family:Calibri\r\n}\r\n--></style></head>\r\n<body class='hmmessage'><div dir='ltr'> \t\t \t   \t\t  </div></body>\r\n</html>",
   "Mime-Version":"1.0",
   "Date":"Thu, 19 Sep 2013 18:11:12 +0000",
   "X-Tmn":"[Skvi/kuHvvUw+DlCaQ0136pus9MAs4jm]",
   "Content-Type":"multipart/mixed; boundary=\"_733f5ac1-abe1-41b0-9f42-03a4ae524b70_\"",
   "body-plain":" \t\t \t   \t\t  ",
   "Subject":"66666"
}

I will eventually code it to grab the attachment URLs and store it into my local file system with another authenticated request. The authentication and calls are not the issue. My issue is working with the returned code above in PHP. I've tried variations and got errors anything from:

PHP Notice: Trying to get property of non-object

and

PHP Warning: Invalid argument supplied for foreach()

When I tried to just use $json->attachments in the loop as opposed to $json2->attachments.

Any help would be great!

هل كانت مفيدة؟

المحلول

You were close. In your JSON object, the URLs are one more level deep. You need access it as below:

foreach ($json2->attachments as $value) {
    echo $value->url;
}

Demo!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top