简体   繁体   English

从HTTP套接字响应获取XML元素的值

[英]Get value of XML element from a HTTP Socket response

I have a controller that sends requests using an HTTP Socket, and gives responses in xml format. 我有一个控制器,它使用HTTP套接字发送请求,并以xml格式给出响应。 I am using cakephp 2.6. 我正在使用cakephp 2.6。
Here is my code to get response body: 这是获取响应正文的代码:

    $HttpSocket = new HttpSocket();            
    $response = $HttpSocket->request($request);
    $resulthit = $response->body;

When I try to print the response body, it returns this in my browser: 当我尝试打印响应正文时,它将在我的浏览器中返回:

-2201502101153512eFXcByWLUHvQmYC0EHMn2JVxcpyzozBcek uid dan pwd

But when I look at the source of page, this is what I see: 但是,当我查看页面源代码时,这就是我看到的内容:

<? xml version="1.0" ?>
  <PUSH>
   <STATUS>-2</STATUS>
   <SMSCMESSAGEID>20150210133953</SMSCMESSAGEID>
   <GUID>knDlIBuUZf6zixlhbbxxLoxhEUGZTWPD</GUID>
   <MSG>cek uid dan pwd</MSG>
  </PUSH>

How I can get value of XML element above? 我如何获得上面XML元素的价值?
I want the STATUS and GUID. 我想要状态和GUID。

I've already tried: 我已经尝试过:

$xml = new SimpleXMLElement($resulthit);

But I only get an error in return that says 但是我只得到一个错误,说

 "String could not be parsed as XML"

You can use the CakePHP Xml class: CakePHP XML class 您可以使用CakePHP Xml类: CakePHP XML类

The reason the code cannot be parsed as XML is because you have < pre > tags surrounding it, Im guessing because you are trying to do debug($something). 无法将代码解析为XML的原因是因为您周围有<pre>标记,我想是因为您正在尝试进行debug($ something)。

At the top of the controller include the XML class: 控制器的顶部包括XML类:

//First Load the Utility Class
App::uses('Xml', 'Utility');

in the controller action do the following: 在控制器动作中执行以下操作:

$this->autoRender = false;
pr(Xml::toArray(Xml::build($thexmlvariable)));

That way you can test it then you should use the ajax layout (A blank layout). 这样,您可以对其进行测试,然后应使用ajax布局(空白布局)。

好吧,最后我得出结论,由于“处理指令目标之前存在空格”,我从Http响应获得的xml无效,我尝试使用有效XML的另一个“虚拟文件响应”,它给出了我想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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