简体   繁体   中英

Can I send a .xml file from .py script to .php script without using API

I am stuck in my project work.

I have to send a .xml file from my python script to .php script without using any API.

What method/modules can I use for this purpose?

The PHP script after receiving the file should ask the user for downloading and download it from browser.

Please guide me with some ideas.

Thanks for any help in advance

If Python and PHP are equipped on same server, consider a straightforward file export/import where the xml content is converted to string and saved as file from Python and then read into PHP:

Python

import xml.etree.ElementTree as ET

xmlstr = '''\
    <data>      
        <example>88</example>        
    </data>'''    
dom = ET.fromstring(xmlstr)

tree_out = ET.tostring(dom, encoding='UTF-8', method='xml')
xmlfile = open('/path/to/Output.xml', 'wb')
xmlfile.write(tree_out)
xmlfile.close()

PHP

// LOAD XML SOURCE
$doc = new DOMDocument();
$doc->load('/path/to/Output.xml');

// ECHO CONTENT
echo $doc->saveXML();

Command Line

You can even call the Python script via command line from PHP using exec() :

exec('python /path/to/Python/Script.py');

// LOAD XML SOURCE
$doc = new DOMDocument();
$doc->load('/path/to/Output.xml');    

// ECHO CONTENT
echo $doc->saveXML();

//<?xml version="1.0"?>
//<data>      
//        <example>88</example>        
//    </data>

And vice versa from Python using subprocess's call or Popen

import subprocess

#... same as above ...

# RUN CHILD PROCESS W/O OUTPUT
subprocess.call(['php', '/path/to/PHP/Script.php'])

# RUN CHILD PROCESS W/ OUTPUT
proc = subprocess.Popen(['php','/path/to/PHP/Script.php'],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

print(stdout.decode("utf-8"))

#<?xml version="1.0"?>
#<data>      
#        <example>88</example>        
#    </data>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM