Hobbyist
Hobbyist

Reputation: 16182

DOMDocument is producing trailing data in XML

I'm trying to create an XML file and then send it as an e-mail as-well as force a download, the problem is that the XML document contains a few random numbers at the end of it, making it useless.

Code:

header('Content-Disposition: attachment;filename=License.xml');
    header('Content-Type: text/xml');
    $document = new DOMDocument('1.0');
    $document->formatOutput = true;
    $element_account = $document->createElement("Account");
    $attr_name = $document->createAttribute("Username");
    $attr_pass = $document->createAttribute("Password");
    $attr_key  = $document->createAttribute("Key");

    $attr_name->value = $user;
    $attr_pass->value = $pass;
    $attr_key->value = $key;

    $element_account->appendChild($attr_name);
    $element_account->appendChild($attr_pass);
    $element_account->appendChild($attr_key);

    $document->appendChild($element_account);

    $file_to_attach = 'tmp/License'.$user.'.xml';

    $document->save($file_to_attach);

    require '../PHPMailer/PHPMailerAutoload.php';

    $pemail = new PHPMailer();
    $pemail->From      = '[email protected]';
    $pemail->FromName  = 'OGServer Licensing';
    $pemail->Subject   = 'Your OGServer License has arrived!';
    $pemail->Body      = 'Thank you for registering your product, you will find your License attached to the e-mail, if you have any questions about how to set up your license, you can view the tutorial here: http://ogserver.net/licensing/tutorial.html';
    $pemail->AddAddress( $email );

    $pemail->AddAttachment($file_to_attach, 'License.xml' );

    $pemail->Send();

    $filepath = realpath($file_to_attach);  

    echo readfile($file_to_attach);

Upvotes: 0

Views: 64

Answers (1)

hakre
hakre

Reputation: 197544

You output those numbers after you've outputted the file to attach. You do that here:

echo readfile($file_to_attach);

It's just that readfile returns the number of bytes read and you then echo that number. Quoting the section titled Return Values:

Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.

As readfile has already output the file's content to STDOUT, you just add the integer number of the file-size (bytes read by readfile) afterwards.


As the file-size actually is not that large, there is even little benefit from using readfile here as it requires you to have the file on disk.

So alternatively you can store the XML into a string:

$licenseXml = $document->saveXML();

And then attach it to the email:

$pemail->AddStringAttachment($licenseXml, 'License.xml');

and then output it:

echo $licenseXml;

That should do it equally well.

Upvotes: 1

Related Questions