PHP 将 XML 转换为 JSON

我尝试在 php 中将 xml 转换为 json。如果使用 simple xml 和 json _ encode 执行简单的转换,则 xml 中的任何属性都不会显示。

$xml = simplexml_load_file("states.xml");
echo json_encode($xml);

所以我试着像这样手动解析它。

foreach($xml->children() as $state)
{
$states[]= array('state' => $state->name);
}
echo json_encode($states);

状态的输出为 {"state":{"0":"Alabama"}}而不是 {"state":"Alabama"}

我做错了什么?

XML:

<?xml version="1.0" ?>
<states>
<state id="AL">
<name>Alabama</name>
</state>
<state id="AK">
<name>Alaska</name>
</state>
</states>

产出:

[{"state":{"0":"Alabama"}},{"state":{"0":"Alaska"}

Var dump:

object(SimpleXMLElement)#1 (1) {
["state"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#3 (2) {
["@attributes"]=>
array(1) {
["id"]=>
string(2) "AL"
}
["name"]=>
string(7) "Alabama"
}
[1]=>
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(1) {
["id"]=>
string(2) "AK"
}
["name"]=>
string(6) "Alaska"
}
}
}
351342 次浏览

看起来 $state->name变量保存着一个数组

var_dump($state)

foreach里面测试一下。

如果是这种情况,您可以将 foreach中的行更改为

$states[]= array('state' => array_shift($state->name));

来纠正它。

我想通了。Json _ encode 处理对象的方式与字符串不同。我将对象强制转换为字符串,它现在工作了。

foreach($xml->children() as $state)
{
$states[]= array('state' => (string)$state->name);
}
echo json_encode($states);

很抱歉回答了一个老的帖子,但是这篇文章概述了一个相对简短、简明和易于维护的方法。我自己测试过,效果很好。

Http://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/

<?php
class XmlToJson {
public function Parse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);


return $json;
}
}
?>

我已经使用了迈尔斯约翰逊的 类型转换器为此目的。它可以安装使用 作曲家

你可以用它写下这样的东西:

<?php
require 'vendor/autoload.php';
use mjohnson\utility\TypeConverter;


$xml = file_get_contents("file.xml");
$arr = TypeConverter::xmlToArray($xml, TypeConverter::XML_GROUP);
echo json_encode($arr);

如果只想将 XML 的特定部分转换为 JSON,可以使用 XPath 检索该部分并将其转换为 JSON。

<?php
$file = @file_get_contents($xml_File, FILE_TEXT);
$xml = new SimpleXMLElement($file);
$xml_Excerpt = @$xml->xpath('/states/state[@id="AL"]')[0]; // [0] gets the node
echo json_encode($xml_Excerpt);
?>

请注意,如果您的 Xpath 是不正确的,这将死于一个错误。因此,如果您正在通过 AJAX 调用调试这个函数,我建议您也记录响应主体。

Json & Array 来自 XML 的三行代码:

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

一个常见的缺陷是忘记了 json_encode()不尊重具有 textvalue 还有属性的元素。它会选择其中之一,意味着数据丢失。 下面的函数解决了这个问题。如果一个人决定走 json_encode/decode的道路,下面的函数是建议。

function json_prepare_xml($domNode) {
foreach($domNode->childNodes as $node) {
if($node->hasChildNodes()) {
json_prepare_xml($node);
} else {
if($domNode->hasAttributes() && strlen($domNode->nodeValue)){
$domNode->setAttribute("nodeValue", $node->textContent);
$node->nodeValue = "";
}
}
}
}


$dom = new DOMDocument();
$dom->loadXML( file_get_contents($xmlfile) );
json_prepare_xml($dom);
$sxml = simplexml_load_string( $dom->saveXML() );
$json = json_decode( json_encode( $sxml ) );

通过这样做,<foo bar="3">Lorem</foo>将不会在您的 JSON 中以 {"foo":"Lorem"}的形式结束。

我想我有点晚了,但我已经编写了一个小函数来完成这个任务。它还负责处理属性、文本内容,即使具有相同节点名的多个节点是兄弟节点也是如此。

免责声明: 我不是一个 PHP 本地人,所以请容忍简单的错误。

function xml2js($xmlnode) {
$root = (func_num_args() > 1 ? false : true);
$jsnode = array();


if (!$root) {
if (count($xmlnode->attributes()) > 0){
$jsnode["$"] = array();
foreach($xmlnode->attributes() as $key => $value)
$jsnode["$"][$key] = (string)$value;
}


$textcontent = trim((string)$xmlnode);
if (count($textcontent) > 0)
$jsnode["_"] = $textcontent;


foreach ($xmlnode->children() as $childxmlnode) {
$childname = $childxmlnode->getName();
if (!array_key_exists($childname, $jsnode))
$jsnode[$childname] = array();
array_push($jsnode[$childname], xml2js($childxmlnode, true));
}
return $jsnode;
} else {
$nodename = $xmlnode->getName();
$jsnode[$nodename] = array();
array_push($jsnode[$nodename], xml2js($xmlnode, true));
return json_encode($jsnode);
}
}

用法例子:

$xml = simplexml_load_file("myfile.xml");
echo xml2js($xml);

示例 Input (myfile.xml) :

<family name="Johnson">
<child name="John" age="5">
<toy status="old">Trooper</toy>
<toy status="old">Ultrablock</toy>
<toy status="new">Bike</toy>
</child>
</family>

输出示例:

{"family":[{"$":{"name":"Johnson"},"child":[{"$":{"name":"John","age":"5"},"toy":[{"$":{"status":"old"},"_":"Trooper"},{"$":{"status":"old"},"_":"Ultrablock"},{"$":{"status":"new"},"_":"Bike"}]}]}]}

印刷精美:

{
"family" : [{
"$" : {
"name" : "Johnson"
},
"child" : [{
"$" : {
"name" : "John",
"age" : "5"
},
"toy" : [{
"$" : {
"status" : "old"
},
"_" : "Trooper"
}, {
"$" : {
"status" : "old"
},
"_" : "Ultrablock"
}, {
"$" : {
"status" : "new"
},
"_" : "Bike"
}
]
}
]
}
]
}

要记住的怪癖: 具有相同标签名的几个标签可以是兄弟标签。除了最后一个兄弟姐妹外,其他解决方案很可能会放弃所有其他解决方案。为了避免这种情况,每个单独的节点(即使它只有一个子节点)都是一个数组,该数组为标签名的每个实例保存一个对象。(参见示例中的多个“”元素)

甚至根元素(其中只有一个应该存在于有效的 XML 文档中)也存储为带有实例对象的数组,只是为了具有一致的数据结构。

为了能够区分 XML 节点内容和 XML 属性,每个对象属性都存储在“ $”和“ _”子节点中的内容中。

编辑: 我忘了显示示例输入数据的输出

{
"states" : [{
"state" : [{
"$" : {
"id" : "AL"
},
"name" : [{
"_" : "Alabama"
}
]
}, {
"$" : {
"id" : "AK"
},
"name" : [{
"_" : "Alaska"
}
]
}
]
}
]
}

试着用这个

$xml = ... // Xml file data


// first approach
$Json = json_encode(simplexml_load_string($xml));


---------------- OR -----------------------


// second approach
$Json = json_encode(simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA));


echo $Json;

或者

您可以使用这个库: https://github.com/rentpost/xml2array

$templateData =  $_POST['data'];


// initializing or creating array
$template_info =  $templateData;


// creating object of SimpleXMLElement
$xml_template_info = new SimpleXMLElement("<?xml version=\"1.0\"?><template></template>");


// function call to convert array to xml
array_to_xml($template_info,$xml_template_info);


//saving generated xml file
$xml_template_info->asXML(dirname(__FILE__)."/manifest.xml") ;


// function defination to convert array to xml
function array_to_xml($template_info, &$xml_template_info) {
foreach($template_info as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_template_info->addChild($key);
if(is_array($value)){
$cont = 0;
foreach(array_keys($value) as $k){
if(is_numeric($k)) $cont++;
}
}


if($cont>0){
for($i=0; $i < $cont; $i++){
$subnode = $xml_body_info->addChild($key);
array_to_xml($value[$i], $subnode);
}
}else{
$subnode = $xml_body_info->addChild($key);
array_to_xml($value, $subnode);
}
}
else{
array_to_xml($value, $xml_template_info);
}
}
else {
$xml_template_info->addChild($key,$value);
}
}
}

这里所有的解决方案都有问题!

... 当表示需要完美的 XML 解释(没有属性问题)和重现所有文本标记-文本-标记-文本-... 和标记的顺序时。还要记住的是,JSON 对象“是一个无序集”(不是重复键,键不能有预定义的顺序) ... 甚至 ZF 的 xml2json也是错误的(!)因为没有完全保留 XML 结构。

这里的所有解决方案都存在这个简单 XML 的问题,

    <states x-x='1'>
<state y="123">Alabama</state>
My name is <b>John</b> Doe
<state>Alaska</state>
</states>

...@FTav 解决方案似乎比3行解决方案更好,但在使用此 XML 进行测试时也没有什么 bug。

旧的解决方案是最好的(为了减少损失)

今天众所周知的 JsonML解决方案被 Zorba 项目和其他人使用,首次在2006年或2007年由(分别) Stephen McKamey约翰 · 斯内尔森提出。

// the core algorithm is the XSLT of the "jsonML conventions"
// see  https://github.com/mckamey/jsonml
$xslt = 'https://raw.githubusercontent.com/mckamey/jsonml/master/jsonml.xslt';
$dom = new DOMDocument;
$dom->loadXML('
<states x-x=\'1\'>
<state y="123">Alabama</state>
My name is <b>John</b> Doe
<state>Alaska</state>
</states>
');
if (!$dom) die("\nERROR!");
$xslDoc = new DOMDocument();
$xslDoc->load($xslt);
$proc = new XSLTProcessor();
$proc->importStylesheet($xslDoc);
echo $proc->transformToXML($dom);

农产品

["states",{"x-x":"1"},
"\n\t    ",
["state",{"y":"123"},"Alabama"],
"\n\t\tMy name is ",
["b","John"],
" Doe\n\t    ",
["state","Alaska"],
"\n\t"
]

参见 http://jsonML.orgGithub.com/mckamey/jsonml。这个 JSON 的产生规则基于 元素 JSON-模拟,

enter image description here

这种语法是 元素定义和递归,使用 < br/> element-list ::= element ',' element-list | element

这是对 Antonio Max 最推崇的解决方案的改进,该解决方案还可以处理具有名称空间的 XML (通过用下划线替换冒号)。它还有一些额外的选项(并且能够正确地解析 <person my-attribute='name'>John</person>)。

function parse_xml_into_array($xml_string, $options = array()) {
/*
DESCRIPTION:
- parse an XML string into an array
INPUT:
- $xml_string
- $options : associative array with any of these keys:
- 'flatten_cdata' : set to true to flatten CDATA elements
- 'use_objects' : set to true to parse into objects instead of associative arrays
- 'convert_booleans' : set to true to cast string values 'true' and 'false' into booleans
OUTPUT:
- associative array
*/


// Remove namespaces by replacing ":" with "_"
if (preg_match_all("|</([\\w\\-]+):([\\w\\-]+)>|", $xml_string, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$xml_string = str_replace('<'. $match[1] .':'. $match[2], '<'. $match[1] .'_'. $match[2], $xml_string);
$xml_string = str_replace('</'. $match[1] .':'. $match[2], '</'. $match[1] .'_'. $match[2], $xml_string);
}
}


$output = json_decode(json_encode(@simplexml_load_string($xml_string, 'SimpleXMLElement', ($options['flatten_cdata'] ? LIBXML_NOCDATA : 0))), ($options['use_objects'] ? false : true));


// Cast string values "true" and "false" to booleans
if ($options['convert_booleans']) {
$bool = function(&$item, $key) {
if (in_array($item, array('true', 'TRUE', 'True'), true)) {
$item = true;
} elseif (in_array($item, array('false', 'FALSE', 'False'), true)) {
$item = false;
}
};
array_walk_recursive($output, $bool);
}


return $output;
}

优化安东尼奥 · 马克斯的回答:

$xmlfile = 'yourfile.xml';
$xmlparser = xml_parser_create();


// open a file and read data
$fp = fopen($xmlfile, 'r');
//9999999 is the length which fread stops to read.
$xmldata = fread($fp, 9999999);


// converting to XML
$xml = simplexml_load_string($xmldata, "SimpleXMLElement", LIBXML_NOCDATA);


// converting to JSON
$json = json_encode($xml);
$array = json_decode($json,TRUE);

在研究了所有这些问题的答案之后,我想出了一个解决方案,它可以很好地跨浏览器使用我的 JavaScript 函数(包括控制台/开发工具) :

<?php


// PHP Version 7.2.1 (Windows 10 x86)


function json2xml( $domNode ) {
foreach( $domNode -> childNodes as $node) {
if ( $node -> hasChildNodes() ) { json2xml( $node ); }
else {
if ( $domNode -> hasAttributes() && strlen( $domNode -> nodeValue ) ) {
$domNode -> setAttribute( "nodeValue", $node -> textContent );
$node -> nodeValue = "";
}
}
}
}


function jsonOut( $file ) {
$dom = new DOMDocument();
$dom -> loadXML( file_get_contents( $file ) );
json2xml( $dom );
header( 'Content-Type: application/json' );
return str_replace( "@", "", json_encode( simplexml_load_string( $dom -> saveXML() ), JSON_PRETTY_PRINT ) );
}


$output = jsonOut( 'https://boxelizer.com/assets/a1e10642e9294f39/b6f30987f0b66103.xml' );


echo( $output );


/*
Or simply
echo( jsonOut( 'https://boxelizer.com/assets/a1e10642e9294f39/b6f30987f0b66103.xml' ) );
*/


?>

它基本上是创建一个新的 DOMDocument,加载和 XML 文件到其中,并遍历每个节点和子节点,获取数据/参数,然后将其导出到 JSON 中,而没有烦人的“@”符号。

链接到 XML文件。

此解决方案处理名称空间、属性,并生成与重复元素一致的结果(始终在数组中,即使只出现一次)。 灵感来自 Ratfactor 的 sxiToArray ()

/**
* <root><a>5</a><b>6</b><b>8</b></root> -> {"root":[{"a":["5"],"b":["6","8"]}]}
* <root a="5"><b>6</b><b>8</b></root> -> {"root":[{"a":"5","b":["6","8"]}]}
* <root xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"><a>123</a><wsp:b>456</wsp:b></root>
*   -> {"root":[{"xmlns:wsp":"http://schemas.xmlsoap.org/ws/2004/09/policy","a":["123"],"wsp:b":["456"]}]}
*/
function domNodesToArray(array $tags, \DOMXPath $xpath)
{
$tagNameToArr = [];
foreach ($tags as $tag) {
$tagData = [];
$attrs = $tag->attributes ? iterator_to_array($tag->attributes) : [];
$subTags = $tag->childNodes ? iterator_to_array($tag->childNodes) : [];
foreach ($xpath->query('namespace::*', $tag) as $nsNode) {
// the only way to get xmlns:*, see https://stackoverflow.com/a/2470433/2750743
if ($tag->hasAttribute($nsNode->nodeName)) {
$attrs[] = $nsNode;
}
}


foreach ($attrs as $attr) {
$tagData[$attr->nodeName] = $attr->nodeValue;
}
if (count($subTags) === 1 && $subTags[0] instanceof \DOMText) {
$text = $subTags[0]->nodeValue;
} elseif (count($subTags) === 0) {
$text = '';
} else {
// ignore whitespace (and any other text if any) between nodes
$isNotDomText = function($node){return !($node instanceof \DOMText);};
$realNodes = array_filter($subTags, $isNotDomText);
$subTagNameToArr = domNodesToArray($realNodes, $xpath);
$tagData = array_merge($tagData, $subTagNameToArr);
$text = null;
}
if (!is_null($text)) {
if ($attrs) {
if ($text) {
$tagData['_'] = $text;
}
} else {
$tagData = $text;
}
}
$keyName = $tag->nodeName;
$tagNameToArr[$keyName][] = $tagData;
}
return $tagNameToArr;
}


function xmlToArr(string $xml)
{
$doc = new \DOMDocument();
$doc->loadXML($xml);
$xpath = new \DOMXPath($doc);
$tags = $doc->childNodes ? iterator_to_array($doc->childNodes) : [];
return domNodesToArray($tags, $xpath);
}

例如:

php > print(json_encode(xmlToArr('<root a="5"><b>6</b></root>')));
{"root":[{"a":"5","b":["6"]}]}

如果你是 ubuntu 用户安装 xml 阅读器(我有 php 5.6。如果您有其他请找到软件包和安装)

sudo apt-get install php5.6-xml
service apache2 restart


$fileContents = file_get_contents('myDirPath/filename.xml');
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$oldXml = $fileContents;
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
This is better solution


$fileContents= file_get_contents("https://www.feedforall.com/sample.xml");
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
$array = json_decode($json,TRUE);
return $array;

发现 FTav 的答案最有用,因为它是非常可定制的,但他的 Xml2js功能有一些缺陷。例如,如果子元素具有相同的标签名,那么它们都将存储在一个对象中,这意味着元素的顺序将不会被保留。在某些情况下,我们确实希望保持顺序,所以我们最好将每个元素的数据存储在一个单独的对象中:

function xml2js($xmlnode) {
$jsnode = array();
$nodename = $xmlnode->getName();
$current_object = array();


if (count($xmlnode->attributes()) > 0) {
foreach($xmlnode->attributes() as $key => $value) {
$current_object[$key] = (string)$value;
}
}


$textcontent = trim((string)$xmlnode);
if (strlen($textcontent) > 0) {
$current_object["content"] = $textcontent;
}


if (count($xmlnode->children()) > 0) {
$current_object['children'] = array();
foreach ($xmlnode->children() as $childxmlnode) {
$childname = $childxmlnode->getName();
array_push($current_object['children'], xml2js($childxmlnode, true));
}
}


$jsnode[ $nodename ] = $current_object;
return $jsnode;
}

初始 xml 结构:

<some-tag some-attribute="value of some attribute">
<another-tag>With text</another-tag>
<surprise></surprise>
<another-tag>The last one</another-tag>
</some-tag>

结果:

{
"some-tag": {
"some-attribute": "value of some attribute",
"children": [
{
"another-tag": {
"content": "With text"
}
},
{
"surprise": []
},
{
"another-tag": {
"content": "The last one"
}
}
]
}
}

最好的解决办法就像魔法一样有效

$fileContents= file_get_contents($url);


$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);


$fileContents = trim(str_replace('"', "'", $fileContents));


$simpleXml = simplexml_load_string($fileContents);


//$json = json_encode($simpleXml); // Remove // if you want to store the result in $json variable


echo '<pre>'.json_encode($simpleXml,JSON_PRETTY_PRINT).'</pre>';

来源

如果 XML 是肥皂文件,则可以使用以下方法:

$xmlStr = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xmlStr);
$xml = new SimpleXMLElement($xmlStr);
return json_encode($xml);
        $content = str_replace(array("\n", "\r", "\t"), '', $response);
$content = trim(str_replace('"', "'", $content));
$xml = simplexml_load_string($content);
$json = json_encode($xml);
return json_decode($json,TRUE);

这招对我很管用

安东尼奥的回答是:

<MyData>
<Level1 myRel="parent" myName="AAA">
<Level2 myRel="child1" myName="BBB">
<Level2 myRel="child2" myName="CCC">
...

你会得到如下数组:

  'Level1' =>
[
0 =>
[
'@attributes' =>
[
'myRel' => 'parent'
'myName'  => 'AAA'
],
'Level2' =>
[
0 =>
[
'@attributes' =>
[
'myRel'  => 'child_1'
'myName'   => 'BBB'
],

所以,如果你想要一个键对数组(而不是 0数字) ,你选择的键,也就是 myName:

  'Level1' =>
[
'AAA' =>
[
'@attributes' =>
[
'myRel' => 'parent'
'myName'  => 'AAA'
],
'Level2' =>
[
'BBB' =>
[
'@attributes' =>
[
'myRel'  => 'child_1'
'myName'   => 'BBB'
],

然后使用 xmlToArrayByKey($xmlContent, 'myName')。代码在这里:

public function xmlToArrayByKey($content, $keyName)
{
try
{
$xml = simplexml_load_string($content, "SimpleXMLElement", LIBXML_NOCDATA );
$array= json_decode( json_encode($xml), TRUE);
return $this->xmlSetChild($array, $keyName);
} catch (Exception $ex) {
return ['xmlerror'=>$ex];
}
}


public function xmlSetChild($array, $keyName, $step=0)
{
$new_array= [];
foreach ($array as $key_1=>$value_1)
{
if (is_array($value_1) && isset($value_1[0]))
{
foreach ($value_1 as $idx=>$value_2)
{
$keyValue = $value_2['@attributes'][$keyName];
$new_array[$key_1][$keyValue] = $this->xmlSetChild($value_2, $keyName, $step+1);
}
}
else{
$new_array[$key_1]=$value_1;
}
}
return $new_array;
}
    //main fuction ===========================
function xml2array($responce)
{
$doc = new DOMDocument();
$doc->loadXML($responce);
$root = $doc->documentElement;
$output = domNodeToArray($root);
$output['@root'] = $root->tagName;
return  $output;
    

}
    

//convert function =====================
function domNodeToArray($node)
{
$output = [];
switch ($node->nodeType) {
case XML_CDATA_SECTION_NODE:
case XML_TEXT_NODE:
$output = trim($node->textContent);
break;
case XML_ELEMENT_NODE:
for ($i = 0, $m = $node->childNodes->length; $i < $m; $i++) {
$child = $node->childNodes->item($i);
$v = domNodeToArray($child);
if (isset($child->tagName)) {
$t = $child->tagName;
if (!isset($output[$t])) {
$output[$t] = [];
}
$output[$t][] = $v;
} elseif ($v || $v === '0') {
$output = (string) $v;
}
}
if ($node->attributes->length && !is_array($output)) { // Has attributes but isn't an array
$output = ['@content' => $output]; // Change output into an array.
}
if (is_array($output)) {
if ($node->attributes->length) {
$a = [];
foreach ($node->attributes as $attrName => $attrNode) {
$a[$attrName] = (string) $attrNode->value;
}
$output['@attributes'] = $a;
}
foreach ($output as $t => $v) {
if (is_array($v) && count($v) == 1 && $t != '@attributes') {
$output[$t] = $v[0];
}
}
}
break;
}
return $output;
}
    

    

    

    

    

    

    

    

    

//REQUEST BY SOAP CLINTE==========================================================
    

$sopeclient = new SoapClient('http://b2b.travel.us/FlightBooking.asmx?wsdl');
$param = array('InputSTR'=>'
<AirSearchQuery>
<Master>
<CompanyId>*****</CompanyId>
<AgentId>1</AgentId>
<BranchId>1</BranchId>
<CoustmerType>AGNT</CoustmerType>
</Master>
<JourneyType>O</JourneyType>
<Currency>USD</Currency>
<Segments>
<Segment id="1">
<Origin>'.$request->depart.'</Origin>
<Destination>'.$request->destination.'</Destination>
<Date>'.$request->departOn.'</Date>
<Time></Time>
</Segment>
</Segments>
</AirSearchQuery>
);
    

                

$responce  = $sopeclient->SearchFare($param);
}
    

//RESPONCE GET ======================================================
     

+"SearchFareResult": "<Itineraries><Itinerary><UniqueID>SK12041915MS7601445MS8750805</UniqueID><TrackID>AAL_LOS_24-02-2022_100_697074770_637812140580760438</TrackID><BaseFare>301.00</BaseFare><Taxes>224.90</Taxes><TotalPrice>525.90</TotalPrice><GrandTotal /><Currency>USD</Currency><FareType>RP</FareType><Adult><NoAdult>1</NoAdult><AdTax>224.9</AdTax><AdtBFare>301.00</AdtBFare></Adult><IndexNumber>0</IndexNumber><Provider>2A</Provider><ValCarrier>MS</ValCarrier><LastTicketingDate /><OutBound>3</OutBound><InBound>0</InBound><Sectors><Sector nearby="" isConnect="" isStopover=""><AirV>SK</AirV><AirlineName>Scandinavian Airlines</AirlineName><AirlineLogoPath>http://www.travelcation.us/AirlineLogo/SKs.gif</AirlineLogoPath><Class>U</Class><CabinClass><Code>Y</Code><Des>ECONOMY</Des></CabinClass><NoSeats>9</NoSeats><FltNum>1204</FltNum><Departure><AirpCode>AAL</AirpCode><Terminal /><Date>24-02-2022</Date><Time>19:15</Time><AirpName>Aalborg</AirpName><CityCode>AAL</CityCode><CityName>Aalborg</CityName><CountryCode>DK</CountryCode><CountryName>Denmark</CountryName><Day>Thu</Day><GEO_Code /></Departure><Arrival><AirpCode>CPH</AirpCode><Terminal>3</Terminal><Date>24-02-2022</Date><Time>20:00</Time><AirpName>Kastrup</AirpName><CityCode>CPH</CityCode><CityName>Copenhagen</CityName><CountryCode>DK</CountryCode><CountryName>Denmark</CountryName><Day>Thu</Day><GEO_Code /></Arrival><EquipType>Canadair Regional Jet CR9</EquipType><ElapsedTime>00:45</ElapsedTime><ActualTime>42:00</ActualTime><TechStopOver>0</TechStopOver><Status>OK</Status><isReturn>false</isReturn><OptrCarrier OptrCarrierDes="Cityjet">WX</OptrCarrier><MrktCarrier MrktCarrierDes="Scandinavian Airlines">SK</MrktCarrier><BaggageInfo>2 pcs</BaggageInfo><TransitTime time="00:00" /></Sector><Sector nearby="" isConnect="" isStopover=""><AirV>MS</AirV><AirlineName>EgyptAir</AirlineName><AirlineLogoPath>http://www.travelcation.us/AirlineLogo/MSs.gif</AirlineLogoPath><Class>V</Class><CabinClass><Code>Y</Code><Des>ECONOMY</Des></CabinClass><NoSeats>9</NoSeats><FltNum>760</FltNum><Departure><AirpCode>CPH</AirpCode><Terminal>3</Terminal><Date>25-02-2022</Date><Time>14:45</Time><AirpName>Kastrup</AirpName><CityCode>CPH</CityCode><CityName>Copenhagen</CityName><CountryCode>DK</CountryCode><CountryName>Denmark</CountryName><Day>Fri</Day><GEO_Code /></Departure><Arrival><AirpCode>CAI</AirpCode><Terminal>3</Terminal><Date>25-02-2022</Date><Time>20:05</Time><AirpName>Cairo Intl.</AirpName><CityCode>CAI</CityCode><CityName>Cairo</CityName><CountryCode>EG</CountryCode><CountryName>Egypt</CountryName><Day>Fri</Day><GEO_Code /></Arrival><EquipType>Boeing 738</EquipType><ElapsedTime>05:20</ElapsedTime><ActualTime>42:00</ActualTime><TechStopOver>0</TechStopOver><Status>OK</Status><isReturn>false</isReturn><OptrCarrier Op
trCarrierDes="EgyptAir">MS</OptrCarrier><MrktCarrier MrktCarrierDes="EgyptAir">MS</MrktCarrier><BaggageInfo>2 pcs</BaggageInfo><TransitTime time="18:45">Connection of 18 Hours 45 Mins in Kastrup, Copenhagen, Denmark</TransitTime></Sector><Sector nearby="" isConnect="" isStopover=""><AirV>MS</AirV><AirlineName>EgyptAir</AirlineName><AirlineLogoPath>http://www.travelcation.us/AirlineLogo/MSs.gif</AirlineLogoPath><Class>L</Class><CabinClass><Code>Y</Code><Des>ECONOMY</Des></CabinClass><NoSeats>5</NoSeats><FltNum>875</FltNum><Departure><AirpCode>CAI</AirpCode><Terminal>3</Terminal><Date>26-02-2022</Date><Time>08:05</Time><AirpName>Cairo Intl.</AirpName><CityCode>CAI</CityCode><CityName>Cairo</CityName><CountryCode>EG</CountryCode><CountryName>Egypt</CountryName><Day>Sat</Day><GEO_Code /></Departure><Arrival><AirpCode>LOS</AirpCode><Terminal>D</Terminal><Date>26-02-2022</Date><Time>13:15</Time><AirpName>Murtala Muhammed</AirpName><CityCode>LOS</CityCode><CityName>Lagos</CityName><CountryCode>NG</CountryCode><CountryName>Nigeria</CountryName><Day>Sat</Day><GEO_Code /></Arrival><EquipType>Boeing 738</EquipType><ElapsedTime>05:10</ElapsedTime><ActualTime>42:00</ActualTime><TechStopOver>0</TechStopOver><Status>OK</Status><isReturn>false</isReturn><OptrCarrier OptrCarrierDes="EgyptAir">MS</OptrCarrier><MrktCarrier MrktCarrierDes="EgyptAir">MS</MrktCarrier><BaggageInfo>2 pcs</BaggageInfo><TransitTime time="12:00">Connection of 12 Hours 0 Mins in Cairo Intl., Cairo, Egypt</TransitTime></Sector></Sectors><FareBasisCodes><FareBasiCode><FareBasis>VOFLOWMS</FareBasis><Airline>MS</Airline><PaxType>ADT</PaxType><Origin /><Destination /><FareRst /></FareBasiCode>
    

    

    

            

//call method===========================================
$xml2json = xml2array($responce->SearchFareResult);
          

print_r($xml2json);
die;


//view result ====================================================


array:3 [▼
"Itinerary" => array:63 [▼
0 => array:17 [▼
"UniqueID" => "SK12041915MS7601445MS8750805"
"TrackID" => "AAL_LOS_24-02-2022_100_946417400_637812150487718359"
"BaseFare" => "301.00"
"Taxes" => "224.90"
"TotalPrice" => "525.90"
"GrandTotal" => []
"Currency" => "USD"
"FareType" => "RP"
"Adult" => array:3 [▼
"NoAdult" => "1"
"AdTax" => "224.9"
"AdtBFare" => "301.00"
]
"IndexNumber" => "0"
"Provider" => "2A"
"ValCarrier" => "MS"
"LastTicketingDate" => []
"OutBound" => "3"
"InBound" => "0"
"Sectors" => array:1 [▼
"Sector" => array:3 [▶]
]
"FareBasisCodes" => array:1 [▶]