-2

I want to get the content text of an xml output. How do I parse this in php? Please see code below.

<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[text]]></MsgType>
  <Content><![CDATA[this is a test]]></Content>
  <MsgId>1234567890123456</MsgId>
</xml>
Jearson
  • 411
  • 1
  • 7
  • 24
  • did you read this ? https://www.php.net/manual/en/function.xml-parse.php – Kamlesh Paul Mar 19 '21 at 05:51
  • @KamleshPaul Yes I read that. But the sample code is not an file, it is an output sent by a server. – Jearson Mar 19 '21 at 05:52
  • Does this answer your question? [How do you parse and process HTML/XML in PHP?](https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – ThW Mar 19 '21 at 08:56

1 Answers1

1

Try this :

$x = '<xml>
         <ToUserName><![CDATA[toUser]]></ToUserName>
         <FromUserName><![CDATA[fromUser]]></FromUserName>
         <CreateTime>1348831860</CreateTime>
         <MsgType><![CDATA[text]]></MsgType>
         <Content><![CDATA[this is a test]]></Content>
         <MsgId>1234567890123456</MsgId>
    </xml>';

$xml = simplexml_load_string($x) or die("Error: Cannot create object");

print_r($xml);
STA
  • 30,729
  • 8
  • 45
  • 59
  • Thanks. I tried to convert the file into array using ```(array)$xml``` But when accessing the ToUserName ```(array)$xml['ToUserName']``` I am getting []. Did I miss something? – Jearson Mar 19 '21 at 06:01
  • Your xml file format is not correct, that's why It can't render properly by php. check here https://rextester.com/MTN54517 – STA Mar 19 '21 at 06:08
  • that is the format of wechat being thrown by their server. – Jearson Mar 19 '21 at 06:17