'How to handle if <![CDATA[ ]]> is null/empty?
I want to convert xml data into JOSN format but there is an issue if I try to do that. simplexml_load_string() returns empty data once after it
perhaps get <![CDATA[ ]]> empty character data
Input Xml data
<channel>
<title>
<![CDATA[shop1]]>
</title>
<link>
<![CDATA[https://www.shop1.com]]>
</link>
<description>
<![CDATA[ ]]>
</description>
<item>
<g:id>1516002</g:id>
<g:title>
<![CDATA[ product 1]]>
</g:title>
</item>
<item>
<g:id>1516003</g:id>
<g:title>
<![CDATA[ product 2 ]]>
</g:title>
</item>
</channel>
Laravel Code:
public function store()
{
$xmlDataString = file_get_contents($this->url);
$xml_file = simplexml_load_string($xmlDataString,'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($xml_file,TRUE);
$array = json_decode($json,TRUE);
dd($array)
//Product::insert($array);
}
output
^ array:2 [▼
"@attributes" => array:1 [▶]
"channel" => array:4 [▼
"title" => "shop1"
"link" => "https://www.shop1.com"
"description" => []
"item" => array:2[▼
0 => []
1 => []
]
]
]
I thought fault raise from <![CDATA[ ]]> here
what is the best way to fetch data from xml to json ?
Solution 1:[1]
If you know clearly about xml file structure, you can use like this code, it works well with cdata:
$this->url = 'xml3.xml';
$xml = file_get_contents($this->url);
$xml = simplexml_load_string($xml);
$title = trim((string) $xml->channel->title);
$description = trim((string) $xml->channel->description);
$result = [];
foreach($xml->channel->item as $item) {
$result [] = [
'id' => trim((string) $item->children('g', TRUE)->id),
'title' => trim((string) $item->children('g', TRUE)->title)
];
}
$all = ['title'=>$title, 'description'=>$description, 'items'=>$result];
dd($all);
Result:
array:3 [?
"title" => "shop1"
"description" => ""
"items" => array:2 [?
0 => array:2 [?
"id" => "1516002"
"title" => "product 1"
]
1 => array:2 [?
"id" => "1516003"
"title" => "product 2"
]
]
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | protoproto |
