我有一个Ruby脚本,它对.NET ASP服务器进行查询,并将结果作为XML字符串;
<?xml version="1.0" encoding="utf-8"?>
<Envelope>
<Body>
<QueryServicesResponse>
<QueryServicesResult>
<Date>2016-01-01</Date>
<serviceList>
<service>
<uuid>10264b70-87ee-11e6-ae22-56b6b6499611</uuid>
<flight>EZY0000</flight>
<originName>London Heathrow</originName>
<originShort>LHR</originShort>
<destinationName>London Stansted</destinationName>
<destinationShort>STN</destinationShort>
<scheduledDeparture>2016-01-01T14:00:00</scheduledDeparture>
<scheduledArrival>2016-01-01T14:30:00</scheduledArrival>
</service>
</serviceList>
</QueryServicesResult>
</QueryServicesResponse>
</Body>
</Envelope>
这是ruby脚本中处理返回体的部分;
# Post the request
resp, data = http.post(path, data, headers)
# Output the results
doc = Nokogiri::XML(resp.body)
doc.remove_namespaces!
puts doc
通过php文件调用ruby脚本,代码如下:
<?php
$xml = exec("ruby test.rb EZY0000",($results));
$xmlparse = simplexml_load_string($xml);
echo $xmlparse;
?>
但是php在尝试解析结果时抛出以下错误;
PHP Warning: simplexml_load_string(): Entity: line 1: parser error : StartTag: invalid element name
PHP Warning: simplexml_load_string(): </Envelope>
我正试图将xml解析成SimpleXMLElement Object
我在过去的几天里一直在尝试各种各样的事情,但现在我对这个问题束手无策。我试过htmlspecialchars
,但也没用。
我唯一能想到的是这与来自ruby脚本的字符串有关,即使它看起来是,并验证为正确的xml。
如果我使用上面的xml并使用下面的php代码,那么一切都如预期的那样工作,我得到了想要的结果;
<?php
$string = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<Envelope>
<Body>
<QueryServicesResponse>
<QueryServicesResult>
<Date>2016-01-01</Date>
<serviceList>
<service>
<uuid>10264b70-87ee-11e6-ae22-56b6b6499611</uuid>
<flight>EZY0000</flight>
<originName>London Heathrow</originName>
<originShort>LHR</originShort>
<destinationName>London Stansted</destinationName>
<destinationShort>STN</destinationShort>
<scheduledDeparture>2016-01-01T14:00:00</scheduledDeparture>
<scheduledArrival>2016-01-01T14:30:00</scheduledArrival>
</service>
</serviceList>
</QueryServicesResult>
</QueryServicesResponse>
</Body>
</Envelope>
XML;
$xml = simplexml_load_string($string);
print_r($xml);
?>
这给了我;
SimpleXMLElement Object
(
[Body] => SimpleXMLElement Object
(
[QueryServicesResponse] => SimpleXMLElement Object
(
[QueryServicesResult] => SimpleXMLElement Object
(
[Date] => 2016-01-01
[serviceList] => SimpleXMLElement Object
(
[service] => SimpleXMLElement Object
(
[uuid] => 10264b70-87ee-11e6-ae22-56b6b6499611
[flight] => EZY0000
[originName] => London Heathrow
[originShort] => LHR
[destinationName] => London Stansted
[destinationShort] => STN
[scheduledDeparture] => 2016-01-01T14:00:00
[scheduledArrival] => 2016-01-01T14:30:00
)
)
)
)
)
)
那么我如何从我的ruby脚本的xml到一个有效的对象,我可以在php操作?有些离线的人说我应该尝试在Rails中完成这一切,但我目前还没有准备好接受这样大的挑战。
因此,在@slowjack2k的提示下,我重新查看了生成响应的Ruby文件。
doc = Nokogiri::XML(resp.body)
,我改变成为doc = Nokogiri::HTML(resp.body)
和低,看它现在工作,并返回一个有效的xml对象在php中预期的