0

I need to transform this XML to proper JSON format using PHP, but nothing I've tried seemed to work. It is a substr-ed version of a SOAP Response.

<item><OBJID>00823006</OBJID><SHORT>PUB0007</SHORT><STEXT>Leading at The Speed of Trust</STEXT><SUTXT/><BEGDA>2015-01-01</BEGDA><ENDDA>2015-12-31</ENDDA></item><item><OBJID>00823016</OBJID><SHORT>PUB0017</SHORT><STEXT>The 5 Choices to Extraordinary Prod.</STEXT><SUTXT/><BEGDA>2015-01-01</BEGDA><ENDDA>2015-12-31</ENDDA></item><item><OBJID>00823020</OBJID><SHORT>PUB0021</SHORT><STEXT>8 Etos Kerja Profesional</STEXT><SUTXT/><BEGDA>2015-01-01</BEGDA><ENDDA>2016-12-31</ENDDA></item><item><OBJID>00823028</OBJID><SHORT>PUB0029</SHORT><STEXT>CSS from Design &amp; Implementation to f/u</STEXT><SUTXT/><BEGDA>2015-01-01</BEGDA><ENDDA>2015-12-31</ENDDA></item>

tried using simplexml_load_string and SimpleXMLElement with examples found through google and always end up with either garbled, malformed json or empty string.

$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response); 
$xml = simplexml_load_string($xml); 
$json = json_encode($xml);

Could someone here help? many thanks in advance

cOle2
  • 4,725
  • 1
  • 24
  • 26

1 Answers1

1

$xml = "
<parent>
<item>
    <OBJID>00823006</OBJID>
    <SHORT>PUB0007</SHORT>
    <STEXT>Leading at The Speed of Trust</STEXT>
    <SUTXT/>
    <BEGDA>2015-01-01</BEGDA>
    <ENDDA>2015-12-31</ENDDA>
</item>
<item>
    <OBJID>00823016</OBJID>
    <SHORT>PUB0017</SHORT>
    <STEXT>The 5 Choices to Extraordinary Prod.</STEXT>
    <SUTXT/>
    <BEGDA>2015-01-01</BEGDA>
    <ENDDA>2015-12-31</ENDDA>
</item>
<item>
    <OBJID>00823020</OBJID>
    <SHORT>PUB0021</SHORT>
    <STEXT>8 Etos Kerja Profesional</STEXT>
    <SUTXT/>
    <BEGDA>2015-01-01</BEGDA>
    <ENDDA>2016-12-31</ENDDA>
</item>
<item>
    <OBJID>00823028</OBJID>
    <SHORT>PUB0029</SHORT>
    <STEXT>CSS from Design &amp; Implementation to f/u</STEXT>
    <SUTXT/>
    <BEGDA>2015-01-01</BEGDA>
    <ENDDA>2015-12-31</ENDDA>
</item>
</parent>";

$xmlFile = simplexml_load_string($xml);
$json = json_encode($xmlFile);

echo $json;

The above seems to work for me. Problem is, is that your XML doesn't have a single parent-element. If you add that, you get proper decoded XML / JSON back.

To add a parent element, you could do the following.

$xml = "<parent>";
$xml .= $xmlToAdd;
$xml .= "</parent>";
Tristan T.
  • 92
  • 1
  • 11