dongwen1935 2017-01-29 07:55
浏览 68
已采纳

在PHP中使用python脚本解析XML

I'm using a python script from with in php to call some xml date from a c# 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?

  • 写回答

1条回答 默认 最新

  • dongxiaoyan4388 2017-01-29 16:35
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64