简体   繁体   中英

Parse XML from python script with in php

I'm using a python script from with in php to call some xml date from ac# server. When I pass it through simplexml_load_string to parse my data. The python script is called for a few different things, but for one of the calls it gives me

Warning: simplexml_load_string(): Entity: line 1: parser error : StartTag: invalid element name

My PHP is:

$output = exec("python Auth.py -M authenticate -p 17df30b0-37c1-4ebf-b45e-39353bd971a9 -P 5b9abe609e1ab31555562dd959fc050d");
$xml = simplexml_load_string($output, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

My Python is:

params = urllib.urlencode(data);
conn = httplib.HTTPConnection("localhost", 8003);
conn.request("POST", path, params)
response = conn.getresponse()
print response.read();

And my XML is:

<?xml version="1.0"?>
<ServerResponse>
  <Result>Success</Result>
  <Token>25027fc3-e3c9-46a8-a1b7-5d217fecfe2c</Token>
</ServerResponse>

I can run my Python script from my Ubuntu command line just fine and I wrote the output into a PHP file as XML data and it worked fine on parsing it.

So I don't know what's wrong. Can anybody help?

You are only capturing the last line of the Python print when assigning exec() to a variable. And this last line is not sufficient to create a SimpleXMLElement with simplexml_load_string .

Instead, pass the output stream into an array using the additional output and return_var arguments of PHP's exec() . Once you receive the $output array, iterate through it to build an XML string:

exec("python Auth.py -M authenticate -p 17df30b0-37c1-4ebf-b45e-39353bd971a9" .
     " -P 5b9abe609e1ab31555562dd959fc050d", $output, $return_var);

$strXML = '';    
foreach ($output as $line) {
    $strXML = $strXML . $line;
}

$xml = simplexml_load_string($strXML, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

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