php
PHP - XML 을 JSON 으로 변환할 수 있는 방법
XML 을 JSON 으로 변환할 수 있는 방법이 있습니다.
아래 코드와 같이 CURL이나 file_get_contents() 로 받은 XML을 simplexml_load_string() 함수로 Parser 한 다음 json_encode()로 JSON 으로 변환합니다. 이것을 다시 json_decode()로 변환해주면 배열로 받을 수 있습니다.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://rss.etnews.com/Section901.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, 0);
$host = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($host);
$json = json_encode($xml);
$str = json_decode($json, true);
print_r($str);
/*
결과
Array
(
[@attributes] => Array (
[version] => 2.0
)
[channel] => Array (
[title] => Array( )
[link] => https://www.etnews.com
[description] => Array( )
[language] => ko
[pubDate] => Sun, 1 Jan 2023 23:33:33 +0900
[lastBuildDate] => Sun, 1 Jan 2023 23:33:33 +0900
[image] => Array (
[title] => Array ( )
[url] => https://img.etnews.com/2020/etnews/images/logo_et.png
[link] => https://www.etnews.com
[description] => Array ( )
)
[item] => Array (
[0] => Array (
[title] => Array ( )
[link] => https://www.etnews.com/20221230000164
[description] => Array ( )
[author] => Array ( )
[guid] => 20221230000164
[comments] => https://www.etnews.com/20221230000164
[pubDate] => Sun, 1 Jan 2023 17:00:00 +0900
)
...
}
}
*/
?>
0 댓글