PHP convert XML to JSON
I figured it out. json_encode handles objects differently than strings. I cast the object to a string and it works now.
foreach($xml->children() as $state)
{
$states[]= array('state' => (string)$state->name);
}
echo json_encode($states);
PHP complex XML to JSON parsing
Generic conversion from XML to JSON fails for more complex XML. XML has attributes as an additional dimension, repeated nodes with the same name or mixed child nodes. JSON based formats like JsonML are possible, but that's not the JSON most people want or expect.
Try a different approach. Read values from the XML using Xpath (and DOM or SimpleXML methods). Build up the variables/data structures just as needed. You can then encode them as JSON.
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$items = [];
// iterate the Table nodes
foreach ($xpath->evaluate('//NewDataSet/Table') as $tableNode) {
$items[] = [
// read CMan_Code as string
'code' => trim($xpath->evaluate('string(CMan_Code)', $tableNode)),
// read CMan_Name as string
'name' => trim($xpath->evaluate('string(CMan_Name)', $tableNode))
];
}
var_dump($items);
// encode the array variable as JSON
var_dump(json_encode($items, JSON_PRETTY_PRINT));
How do I Convert XML to JSON
First of all, please check out this PHP's built-in function simplexml_load_string in the doc to see what parameters does this function take and why? As your xml string is using namespace so you have to provide the namespace as the 4th argument. Look at the code below:
<?php
$xml_string = <<<EOR
<?xml version="1.0" encoding="UTF-8"?>
<ns0:COMMAND xmlns:ns0="http://www.tibco.com/schemas/pinless/PINLESS.core/C2STransferBillPayment/Schema.xsd9">
<ns0:TYPE>EXRCTRFRESP</ns0:TYPE>
<ns0:TXNSTATUS>200</ns0:TXNSTATUS>
<ns0:DATE>02/02/20</ns0:DATE>
<ns0:EXTREFNUM>20200202192308729Af9cWtvg3W</ns0:EXTREFNUM>
<ns0:TXNID>R200202.1923.250008</ns0:TXNID>
<ns0:MESSAGE>R200202.1923.250008 confirmed. </ns0:MESSAGE>
</ns0:COMMAND>
EOR;
$xml = simplexml_load_string($xml_string, "SimpleXMLElement", LIBXML_NOCDATA, 'ns0', true);
$json = json_encode($xml);
$array = json_decode($json, true);
echo '<pre>';
print_r($array);
// Outputs
Array
(
[TYPE] => EXRCTRFRESP
[TXNSTATUS] => 200
[DATE] => 02/02/20
[EXTREFNUM] => 20200202192308729Af9cWtvg3W
[TXNID] => R200202.1923.250008
[MESSAGE] => R200202.1923.250008 confirmed.
)
BTW you can do that using xml file too. In that case, you need to use this function simplexml_load_file()
the same way.
<?php
$xml_file = 'your_xml_file_location.xml';
$xml = simplexml_load_file($xml_file, "SimpleXMLElement", LIBXML_NOCDATA, 'ns0', true);
PHP Converting from XML to JSON with a SimpleXML object. Array with items tag causing issues
A generic conversion has no possibility to know that a single element should be an array in JSON.
SimpleXMLElement
properties can be treated as an Iterable to traverse sibling with the same name. They can be treated as an list or a single value.
This allows you to build up your own array/object structure and serialize it to JSON.
$xml = <<<'XML'
<apns>
<item>
<apn>apn1</apn>
</item>
<item>
<apn>apn2</apn>
</item>
</apns>
XML;
$apns = new SimpleXMLElement($xml);
$json = [
'apns' => []
];
foreach ($apns->item as $item) {
$json['apns'][] = ['apn' => (string)$item->apn];
}
echo json_encode($json, JSON_PRETTY_PRINT);
This still allows you to read/convert parts in a general way. Take a more in deep look at the SimpleXMLElement class. Here are method to iterate over all children or to get the name of the current node.
How to convert XML to JSON in PHP
Is your XML always in that structure? Trying to write a universal XML to JSON translator is much, much harder than writing one for your specific use case.
If it's always the same, just pick out the parts you need from the JSON structure by name, and put them in an array in whatever structure you want. For the XML input and JSON output you give in the question, the code is as simple as this:
$sx = simplexml_load_string($xml);
$output = [];
foreach ( $sx->Variable as $variable ) {
$output[] = [
'Name' => (string)$variable['Name'],
'Comment' => (string)$variable['Comment'],
'EvaluatedDefinition' => (string)$variable['EvaluatedDefinition'],
'#text' => (string)$variable
];
}
echo json_encode($output, JSON_PRETTY_PRINT);
Note the use of (string)
to tell SimpleXML that you want the text content of an element or attribute, rather than an object representing it.
XML to JSON or array? PHP
http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/
Related Topics
Mvc For Advanced PHP Developers
How to Sort Files by Date in PHP
Difference Between Http_Host and Server_Name in PHP
How to Get Id of the Last Updated Row in MySQL
How to Solve PHP Error 'Notice: Array to String Conversion In...'
How to Use Pdo Connection in Other Classes
How to Get the Current Date and Time in PHP
Laravel Requires the Mcrypt PHP Extension
Invoking a PHP Script from a MySQL Trigger
PHP $_Post Array Empty Upon Form Submission
MySQL Connection Not Working: 2002 No Such File or Directory
Working With Large Numbers in PHP
PHP Preg_Match With Working Regex
How to Choose an Authentication Library For Codeigniter
Continue Processing PHP After Sending Http Response