How to Convert Xml into Array in PHP

How to convert XML into array in PHP?

Another option is the SimpleXML extension (I believe it comes standard with most php installs.)

http://php.net/manual/en/book.simplexml.php

The syntax looks something like this for your example

$xml = new SimpleXMLElement($xmlString);
echo $xml->bbb->cccc->dddd['Id'];
echo $xml->bbb->cccc->eeee['name'];
// or...........
foreach ($xml->bbb->cccc as $element) {
foreach($element as $key => $val) {
echo "{$key}: {$val}";
}
}

How to convert XML into the array with PHP?

You can json_encode() then json_decode() as array and use simplexml_load_string()

Steps:

1) First convert your XML into readable string object using simplexml_load_string().

2) Then json_encode() it.

3) json_decode() it, with second parameter TRUE, which will return array instead of object.

4) Now, your XML is converted into an array.

5) Take a blank array, loop over array from above code and append elements to it.

To get desired output:

<?php
$xml = '<?xml version = "1.0" encoding = "utf-8"?>
<tutorialspoint>

<course category = "JAVA">
<title lang = "en">Java</title>
<tutor>Gopal</tutor>
<duration>3</duration>
<price>$30</price>
</course>

<course category = "HADOOP">
<title lang = "en">Hadoop</title>.
<tutor>Satish</tutor>
<duration>3</duration>
<price>$50</price>
</course>

<course category = "HTML">
<title lang = "en">html</title>
<tutor>raju</tutor>
<duration>5</duration>
<price>$50</price>
</course>

<course category = "WEB">
<title lang = "en">Web Technologies</title>
<tutor>Javed</tutor>
<duration>10</duration>
<price>$60</price>
</course>
</tutorialspoint>';

$arr = [];
$array = json_decode(json_encode(simplexml_load_string($xml)),true);
if ( ! empty($array)) {
$i=0;
foreach ($array['course'] as $elem) {
$arr[$i]['title'] = $elem['title'];
$arr[$i]['tutor'] = $elem['tutor'];
$arr[$i]['duration'] = $elem['duration'];
$arr[$i]['price'] = $elem['price'];
++$i;
}
}
echo '<pre>';print_r($arr);echo '</pre>';

Output:

Array
(
[0] => Array
(
[title] => Java
[tutor] => Gopal
[duration] => 3
[price] => $30
)

[1] => Array
(
[title] => Hadoop
[tutor] => Satish
[duration] => 3
[price] => $50
)

[2] => Array
(
[title] => html
[tutor] => raju
[duration] => 5
[price] => $50
)

[3] => Array
(
[title] => Web Technologies
[tutor] => Javed
[duration] => 10
[price] => $60
)

)

Working Code:

How to convert xml file to php array?

simplexml_load_string returns an SimpleXMLElement object. You can query the object (search your data) by using the xpath() function.

Because of how your XML file is set up, the values are set as attributes.
So you need to retrieve the attributes before you can read them.

    <?php

$get = file_get_contents('http://xxx.pl/tmp/tabela.xml');
$arr = simplexml_load_string($get);
$data = $arr->xpath('tabela/druzyna');

?>
<table>
<tr>
<th>pozycja</th>
<th>pkt</th>
<th>mecze</th>
<th>zwyciestwa</th>
<th>porazki</th>
<th>wygrane w domu</th>
<th>przegrane w domu</th>
<th>wygrane na wyjezdzie</th>
<th>przegrane na wyjezdzie </th>
<th>kosze zdobyte</th>
<th>kosze stracone</th>
<th>stosunek zdobytych punktów do straconych punktów</th>
<th>pelna nazwa klubu</th>
<th>logo klubu</th>
</tr>

<?php foreach($data as $row) : ?>
<?php
$row = $row->attributes();
?>
<tr>
<td><?php echo $row->pozycja ?></td>
<td><?php echo $row->pkt ?></td>
<td><?php echo $row->mecze ?></td>
<td><?php echo $row->zwyciestwa ?></td>
<td><?php echo $row->porazki ?></td>
<td><?php echo $row->wygrane_dom ?></td>
<td><?php echo $row->przegrane_dom ?></td>
<td><?php echo $row->wygrane_wyjazd ?></td>
<td><?php echo $row->przegrane_wyjazd ?></td>
<td><?php echo $row->kosze_zdobyte ?></td>
<td><?php echo $row->kosze_stracone ?></td>
<td><?php echo $row->stosunek_zdob_strac ?></td>
<td><?php echo $row->pelna_nazwa ?></td>
<td><?php echo $row->logo; ?></td>
</tr>
<?php endforeach;?>
</table>

XML to Array? [PHP]

You can't access children by using a foreach on the node itself, you need to use .children():

$s =<<<EOS
<root>
<Formula>
<formulaname>Basic</formulaname>
<movespeed>1</movespeed>
<box>4</box>
<chicken>3</chicken>
<ducks>1</ducks>
<cereal>2</cereal>
</Formula>
</root>
EOS;

$xml = simplexml_load_string($s);

foreach ($xml->Formula as $element) {
foreach($element->children() as $key => $val) {
echo "{$key}: {$val}";
}
}

How to convert XML to Array In PHP

try the following to xml response to an array

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



echo "<pre>";print_r($responseArray);

Output

Array
(
[soapBody] => Array
(
[ns2setTransactionResponse] => Array
(
[return] => Array
(
[merchantReference] => mercRef_1395758213
[payUReference] => 17613281409117
[successful] => true
)

)

)

)

Converting XML file elements into a PHP array

This should return the fully accessible array:

$get = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($get);
print_r($arr);

You can now access items like this:

echo $arr->groupID64;
echo $arr->members->steamID64;

Edit:
To parse the streamID, you can do a for loop

$ids = $arr->members->steamID64;
foreach($ids as $id) {
echo $id;
}

PHP - XML Response into Array

To work with a XML file you have to use a XML Parser. In this answer, you'll see how to use SimpleXML Parser. To encode data in JSON format, you can use json_encode function.

First of all, you have to know the specific structure of your own XML file/string. Under <CompressedInventoryResults> you have this structure:

<CompressedVehicles>
<F> <!-- attributes legend -->
<RS>
<R>
<VS>
<V /> <!-- vehicle -->
<V /> <!-- vehicle -->
</VS>
</R>
</RS>
</F>
</CompressedVehicles>

Then, there are other system nodes not useful in this example: <ErrorMessage/>...

Basically, converting a XML in JSON format using SimpleXML can be a very simple task:

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

By this easy way, you obtain in $json variable a JSON string like this:

{
"CompressedVehicles": {
"F": {
"@attributes": { ... },
"RS": {
"R": {
"@attributes": { "_ID": "9002250" },
"VS": {
"V": [
{
"@attributes": { ... }
},
{
"@attributes": { ... }
}
]
}
}
}
}
},
"ErrorMessage": {},
"InventoryResultType": "OK",
"IsSuccess": "true"
}

pastebin complete JSON

Re-decoding it:

$data = json_decode( $json );

you can add/modify/delete/print various elements using standard php syntax for objects and array.

So, i.e., following two lines:

echo $data->CompressedVehicles->F->{'@attributes'}->_0) . PHP_EOL;
echo $data->CompressedVehicles->F->{'@attributes'}->_1) . PHP_EOL;

will output:

vin
stock

Otherwise, if you want access to vehicles data, you can do it through a foreach loop:

foreach( $data->CompressedVehicles->F->RS->R->VS->V as $vehicle )
{
echo $vehicle->{'@attributes'}->_0 . PHP_EOL;
echo $vehicle->{'@attributes'}->_1 . PHP_EOL;
}

output:

WA1CMAFP3FA096506
A096506
WAU3GAFD2FN030313
A030313

Creating a custom JSON using SimpleXML

A (bit) more complex operation can be to obtain your desired JSON, especially due the weird structure of XML, that use codified attributes.

After loading your XML string:

$xml = simplexml_load_string( $xmlString );

you can navigate in the XML structure. The SimpleXML syntax is very similar to php StdObject syntax: to select a node level you have to use ->nodeName; to access to a single node as same level you can use array syntax (->nodeName[0]); to access to a specific attribute node you can use array syntax (->nodeName[0]['attributeName']).

So, to select <CompressedVehicles> node with all its children:

$CompressedVehicles = $xml->CompressedVehicles;

To echo a node as XML:

echo $CompressedVehicles->F->RS->R->VS->V[0]->asXML();
# ↑ only first vehicle

output:

<V _0="WA1CMAFP3FA096506" _1="A096506" _2="54305" _3="New" ... />

As mentioned before, you have to create a legend for attributes, that are listed in <F> node:

<F _0="vin" _1="stock" _2="msrp" _3="type" _4="year" _5="make" _6="model" _7="imagelist" _8="stockimage"> 

To do this, you can fill an array iterating <F> node attributes:

$attributes = array();
foreach( $CompressedVehicles->F->attributes() as $key => $val )
{
$attributes[$key] = $val->__toString();
}

Now, in $attributes array, you have this:

Array
(
[_0] => vin
[_1] => stock
[_2] => msrp
[_3] => type
[_4] => year
[_5] => make
[_6] => model
[_7] => imagelist
[_8] => stockimage
)

It's the moment to init the main array:

$data = array();

Then you can perform a foreach loop through all <V> nodes and fill a sub-array using the keys from $attributes:

foreach( $CompressedVehicles->F->RS->R->VS->V as $vehicle )
{
$line = array();
foreach( $vehicle->attributes() as $key => $val )
{
$line[$attributes[$key]] = $val->__toString();
}

While you're at it, why don't explode images element?

    $line['imagelist'] = explode( '|', $line['imagelist'] );

At this point, you can add sub-array to main array:

    $data[] = $line;
}

You can note the ->__toString() syntax to cast a SIMPLEXMLElement object to string.

Now, in your $data you have this:

Array
(
[0] => Array
(
[vin] => WA1CMAFP3FA096506
[stock] => A096506
[msrp] => 54305
[type] => New
[year] => 2015
[make] => Audi
[model] => Q5
[imagelist] => Array ( ... )
[stockimage] =>
)
[1] => Array ( ... )
)

pastebin complete array structure

And you can encode it in a JSON string format:

$json = json_encode( $data );

$json contains (prettified):

[
{
"vin": "WA1CMAFP3FA096506",
"stock": "A096506",
"msrp": "54305",
"type": "New",
"year": "2015",
"make": "Audi",
"model": "Q5",
"imagelist": [
"http:\/\/content.homenetiol.com\/640x480\/53ef04aa3c46463aaa4fd91b13c00037.jpg",
...
],
"stockimage": ""
},
{
"vin": "WAU3GAFD2FN030313",
...
}
]

pastebin complete JSON

how to convert xml result into array

Can try using simplexml_load_string(). Enclose your whole xml by a parent tag. Here I included <myxml>...</myxml>. Example:

$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<myxml>
<entry>
<string>actiontypedesc</string>
<string>Registration of google1231.com for 1 year</string>
</entry>
<entry>
<string>unutilisedsellingamount</string>
<string>-1531.770</string>
</entry>
<entry>
<string>sellingamount</string>
<string>-1531.770</string>
</entry>
<entry>
<string>entityid</string>
<string>57928339</string>
</entry>
<entry>
<string>actionstatus</string>
<string>Success</string>
</entry>
</myxml>";

$xml = json_decode(json_encode(simplexml_load_string($myXMLData)), true);
// json_encode() & json_decode() is to convert object to array
print '<pre>';
print_r($xml);
print '</pre>';

How to convert this XML request into array in php?

Put this class for converting xml to array make a file named as "xmlParser.class.php" copy paste below code to it.

<?php
/**
* xmlParser
*
* @author shashank Patel
*/

class xmlParser
{
public $ssBlankShow = true;

/**
* @todo convert xml to array
* @param string $contents
* @param string $get_attributes
* @param string $priority
* @access public
* @return mixed
*/
public function xml2array($contents, $get_attributes=1, $priority = 'tag')
{
if(!$contents)
return array();

if(!function_exists('xml_parser_create'))
{
return array();
}

$parser = xml_parser_create('');
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents), $xml_values);
xml_parser_free($parser);

if(!$xml_values)
return;

$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();

$current = &$xml_array;

$repeated_tag_index = array();

foreach($xml_values as $data)
{
unset($attributes,$value);

extract($data);

$result = array();

$attributes_data = array();

if(isset($value))
{
if($priority == 'tag')
$result = $value;
else
$result['value'] = $value;
}

if(isset($attributes) and $get_attributes)
{
foreach($attributes as $attr => $val)
{
if($priority == 'tag')
$attributes_data[$attr] = $val;
else
$result['attr'][$attr] = $val;
}
}

if($type == "open")
{
$parent[$level-1] = &$current;
if(!is_array($current) or (!in_array($tag, array_keys($current))))
{
$current[$tag] = $result;

if($attributes_data)
$current[$tag. '_attr'] = $attributes_data;

$repeated_tag_index[$tag.'_'.$level] = 1;

$current = &$current[$tag];

}
else
{
if(isset($current[$tag][0]))
{
$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;

$repeated_tag_index[$tag.'_'.$level]++;
}
else
{
$current[$tag] = array($current[$tag],$result);

$repeated_tag_index[$tag.'_'.$level] = 2;

if(isset($current[$tag.'_attr']))
{
$current[$tag]['0_attr'] = $current[$tag.'_attr'];

unset($current[$tag.'_attr']);
}

}
$last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
$current = &$current[$tag][$last_item_index];
}

}
elseif($type == "complete")
{
if(!isset($current[$tag]))
{
$current[$tag] = $result;
$repeated_tag_index[$tag.'_'.$level] = 1;
if($priority == 'tag' and $attributes_data)
$current[$tag. '_attr'] = $attributes_data;

}
else
{
if(isset($current[$tag][0]) and is_array($current[$tag]))
{
$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;

if($priority == 'tag' and $get_attributes and $attributes_data)
{
$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
}

$repeated_tag_index[$tag.'_'.$level]++;

}
else
{

$current[$tag] = array($current[$tag],$result);

$repeated_tag_index[$tag.'_'.$level] = 1;

if($priority == 'tag' and $get_attributes)
{
if(isset($current[$tag.'_attr']))
{
$current[$tag]['0_attr'] = $current[$tag.'_attr'];
unset($current[$tag.'_attr']);
}

if($attributes_data)
{
$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
}
}
$repeated_tag_index[$tag.'_'.$level]++;
}
}

}
elseif($type == 'close')
{
$current = &$parent[$level-1];
}
}

return($xml_array);
}

/**
* @todo convert array to xml
* @param mixed $array
* @param string $level
* @param string $KeyForBlank
* @access public
* @return mixed
*/
public function array_to_xml($array, $level=1, $KeyForBlank = 'row')
{
$xml = '';

if ($level==1)
{
$xml .= '<?xml version="1.0" encoding="UTF-8"?>'.
"<musicbox><response>";
}
else if($level==11)
{
$xml .= '<?xml version="1.0" encoding="UTF-8"?>'."\n".
"<xml>";
}
foreach ($array as $key=>$value)
{

$key = strtolower($key);
$eleKey = $key;

if (is_array($value))
{
if(sizeof($value)) {
if ( preg_match('/^\d+$/', $eleKey) ) $eleKey = $KeyForBlank;
$xml .= str_repeat("",$level)."<$eleKey>";
$level++;
$xml .= $this->array_to_xml($value, $level, $KeyForBlank);
$level--;
$xml .= str_repeat("",$level)."</$eleKey>";
}
else
{
if($eleKey == 'genre' || $this->ssBlankShow == true)
$xml .= str_repeat("",$level)."<$eleKey></$eleKey>";
else
$xml .= str_repeat("",$level)."<$eleKey />";
}
}
else
{
if (trim($value)!='')
{
if ( preg_match('/^\d+$/', $eleKey) ) $eleKey = $KeyForBlank;
if (htmlspecialchars($value)!=$value || $this->otherchar($value))
{
$xml .= str_repeat("",$level).
"<$eleKey>$value</$eleKey>";
}
else
{
$xml .= str_repeat("",$level).
"<$eleKey>$value</$eleKey>";
}
}
else
{
if($eleKey == 'genre' || $this->ssBlankShow == true)
$xml .= str_repeat("",$level)."<$eleKey></$eleKey>";
else
$xml .= str_repeat("",$level)."<$eleKey />";
}
}
}
if ($level==1)
{
$xml .= "</response></musicbox>";
}
else if($level==11)
{
$xml .= "</xml>";
}
return $xml;
}
/**
* @todo remove other char ('/\:/')
* @param string $str
* @access public
* @return mixed
*/


public function otherchar($str)
{
return preg_match('/\:/', $str);
}

}

After that make a file named as "test.php" that contains below code:

<?php

$ssString = '<OTA_HotelAvailRQ Version="1.0"><POS><Source><UniqueId Id="20000704abcde:105ABCDE" /></Source></POS><AvailRequestSegments><AvailRequestSegment><StayDateRange End="2011-08-15" Start="2011-08-14" />
<RoomStayCandidates><RoomStayCandidate Quantity="1"><GuestCounts><GuestCount AgeQualifyingCode="10" Count="1" /></GuestCounts></RoomStayCandidate></RoomStayCandidates>
<HotelSearchCriteria><Criterion><HotelRef Destination="East London, South Africa" CityCode="" CountryCode="" HotelName="" MinHotelRating="1"/><SearchCurrency>EUR</SearchCurrency>
<AdditionalInfo Value="1" /><Language>EN</Language></Criterion></HotelSearchCriteria></AvailRequestSegment></AvailRequestSegments></OTA_HotelAvailRQ>';

include 'xmlParser.class.php';

$oXmlParser = new xmlParser();
$asArray = $oXmlParser->xml2array($ssString);
$asArray1 = $oXmlParser->xml2array($ssString,'');
$asArray2 = $oXmlParser->xml2array($ssString,1,'');
echo "<pre>";
print_r($asArray);
exit;
?>

Try this if any inconvenience please inform me if i can help you more.

Here is three different kind array you got by changing parameters like below use whatever satisfy your demand.

$asArray = $oXmlParser->xml2array($ssString);

$asArray1 = $oXmlParser->xml2array($ssString,'');

$asArray2 = $oXmlParser->xml2array($ssString,1,'');


Related Topics



Leave a reply



Submit