PHP - 获取在另一个PHP文件中回显的XML文件,然后将回显的XML输出保存到服务器

I have an PHP file - called xml_generate.php - that creates a DOM object and echoes it at the very end.

Lets say it looks like this:

header("Content-type: text/xml"); 

$dom = new DOMDocument('1.0');
$node = $dom->createElement('foo');
$root = $dom->appendChild($node);

$node = $dom->createElement('bar');
$new_node = $root->appendChild($node);

echo $dom->saveXML();

I'm accessing this file from jQuery and displaying the content on the client-side. The actual xml_generate.php creates the DOM dynamically from a database.

However, I want to have a PHP file that will create a backup of the XML generated by generate_xml.php and save it to the server.

So, I need to somehow access that XML document (the one that is dynamically created in xml_generate.php).

I've tried a a few different functions to get the XML from xml_generate.php, for instance:

$xml = http_get('xml_generate.php');,

$xml = file_get_contents('xml_generate.php');

as well as just including the first file (include('xml_generate.php'), then just trying to access the $dom variable in that file).

but I can't seem to get it right. Any ideas on the best approach to do this?

You could use Output Buffering, which will buffer any data sent to the output stream, and then retrieve that after including your script:

ob_start();
include "xml_generate.php";
$xml = ob_get_contents();
ob_end_clean();

Make sure to catch errors @"xml_generate.php" though, or these will be buffered as well and you'll end up with an invalid xml backup.