Emailing array data

Discussion in 'PHP' started by sipherz, Sep 7, 2011.

  1. #1
    Hi

    I have an array of data, that I'd like to send as the body part of an email.

    The code I have so far is:

    
    $items = array();
    foreach($xmlData->Item as $item)
    {
         //do some stuff here
    }
    
    $to = "test@example.com";
    $subject = "Import Successful";
    foreach($items as $record)
    {
        $body .= $record;
    }
     if (mail($to, $subject, $body)) {
       echo("<p>Message successfully sent!</p>");
      } else {
       echo("<p>Message delivery failed...</p>");
      }
    
    Code (markup):
    But I get that $body is undefined.

    Any ideas what I'm doing wrong?
     
    sipherz, Sep 7, 2011 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,899
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #2
    You need to have

    $body = '';

    before you start adding to it. Apart from that your script is just fine.

    To make it a bit more readable change
    foreach($items as $record){
        $body .= $record;
    }
    PHP:
    to
    foreach($items as $record){
        $body .= $record . "\n";
    }
    PHP:
    \n puts a line break after every record and has to be in double quotes.
     
    sarahk, Sep 7, 2011 IP
  3. sipherz

    sipherz Peon

    Messages:
    7
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Ok, so I added the bits of code you mentioned, but the $body part of the email is still blank.

    Any ideas why?

    Thanks

    UPDATED

    The problem was I need to access the array data like

    
    $body .= $record->Name
    
    Code (markup):
    All is working fine now

    Thanks
     
    sipherz, Sep 7, 2011 IP
    sarahk likes this.
  4. freelanceinphp

    freelanceinphp Member

    Messages:
    134
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    48
    #4
    can you please debug $record array, I think it's empty. check your $items variable values.
     
    freelanceinphp, Sep 7, 2011 IP
  5. sarahk

    sarahk iTamer Staff

    Messages:
    28,899
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #5
    What problem do you think remains?
     
    sarahk, Sep 7, 2011 IP