title: Parsing JSON Response in PHP
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Here is what I have so far for the PHP script</p>
  
  <pre><code>// Grab contents of message ( Already in JSON format (i think ? ))
  $json = file_get_contents($api_url);
  $json2 = json_decode($json);
  
  foreach($json2-&gt;attachments-&gt;url AS $attach) {
  
      file_put_contents('test.txt', $attach, FILE_APPEND);
  
  }
  </code></pre>
  
  <p>The <code>$json</code> variable returns the following (redacted most of the unnecessary code):</p>
  
  <pre><code>{
     "attachments":[
        {
           "url":"fullMailGunURLtoAttachment.jpg",
           "content-type":"image/jpeg",
           "name":"logo-lrg.jpg",
           "size":45465
        }
     ],
     "body-html":"&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;style&gt;&lt;!--\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--&gt;&lt;/style&gt;&lt;/head&gt;\r\n&lt;body class='hmmessage'&gt;&lt;div dir='ltr'&gt; \t\t \t   \t\t  &lt;/div&gt;&lt;/body&gt;\r\n&lt;/html&gt;",
     "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"
  }
  </code></pre>
  
  <p>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:</p>
  
  <blockquote>
    <p>PHP Notice:  Trying to get property of non-object</p>
  </blockquote>
  
  <p>and</p>
  
  <blockquote>
    <p>PHP Warning:  Invalid argument supplied for foreach()</p>
  </blockquote>
  
  <p>When I tried to just use <code>$json-&gt;attachments</code> in the loop as opposed to <code>$json2-&gt;attachments</code>.</p>
  
  <p>Any help would be great!</p>