Óscar Grande Óscar Grande - 4 months ago 7
JSON Question

Send an email using PHP, HTML and JSON

I want to send an email automatically using some static and some dynamic data. So this is the process:


  1. In my main
    *.php
    I´m fetching the data from my ddbb and
    creating the JSON.

  2. I´m sending this JSON to another
    *.php
    to manage this data an
    insert it in my
    <html>
    (Second
    *.php
    ).

  3. Again in the first *.php I´m preparing the mail options and sending
    it. Here is the code.



first.php


...
$query1= mysqli_query($connect, "SELECT * FROM table1 WHERE id='".$field1."'");
$row1= mysqli_fetch_array($query1);
$data_row1[] = $row1;

$query2= mysqli_query($connect, "SELECT * FROM table2 WHERE id='".$field2."'");
$row2= mysqli_fetch_array($query2);
$data_row2[] = $row2;

$data = array(
"data_row1" => $data_row1,
"data_row2" => $data_row2
);

$json_data = json_encode($data);
$url = 'https://webpage.com/folder/second.php?';
$variables = 'data='.$json_data;

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $variables);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$email_text = curl_exec($ch);
curl_close($ch);


Then, in the
second.php
:


<?php
$result = $_GET['data'];
$data = json_decode($result);

$row_data1[] = $data['row_data1'];
$row_data2[] = $data['row_data2'];
$name= $row_data1['var1']." ".$row_data1['var2'];
$city= $row_data2['var2'];
...
?>
<html>
... Some html printing the dynamic values using <?php echo $name; ?>
</html>


Finally, again in the
first.php


...
$to = $destionation_email;
$subject = "The email subject";
$headers = "From: noreply@webpage.com".strip_tags($_POST['req-email']) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

mail($to, $subject, $email_text, $headers);


But my problem is that
second.php
is not fetching the JSON and the email is only showing the static
html
, without any data.

Any solution to fetch the JSON from the
second.php
?

Answer

Well, finally I´ve decided to do everything in the same *.php, so I don´t need to send and receive anything.

The way I´m creating the HTML with dynamic values is:

$email_text = 
    '<html>
        <body>
        ...
            <strong>'.$variable1.'</strong>
        </body>
    </html>';

It´s a pretty long HTML message, but I wasn´t able to do using the other way. I will keep this question opened just in case someone knows another method to do.

Comments