Jakadinho
Jakadinho

Reputation: 701

PHP parsing json from xml file

I'm somewhat familliar with xml and json parsing but Im having a problem with this site. I tried

$json_string="http://meteo.arso.gov.si/uploads/probase/www/plus/timeline/timeline_radar_si_short.xml"; 
$json = file_get_contents($json_string); 
$arr=json_decode($json_string, true);

but it doesn't work. When i was analysing the data i found that there are some javascript variables inside json that are turned to data when javascript is run so maybe thats why it doesn't work. Not shure how to fix it thou.

What I would like to do is parse values like "9:10 CEST"... and "si0_20140930-0710_zm_si.jpg"... into php array.

Upvotes: 1

Views: 397

Answers (3)

Nitin Nain
Nitin Nain

Reputation: 5483

The following solution works. Don't know if there's a better way to do it:

<?php
    $xml_string="http://meteo.arso.gov.si/uploads/probase/www/plus/timeline/timeline_radar_si_short.xml"; 
    $xml = file_get_contents($xml_string);

    // Extract relevant section out of the file
    $start_pos = strpos($xml, "timeline:") + strlen("timeline:");
    $end_pos = strpos($xml, "});");
    $json = substr($xml, $start_pos, $end_pos - $start_pos);

    // Some string replace operations to bind the keys and values within " (double quotes) 
    $json = preg_replace("/(,[a-z]+)/", '"$1', $json);
    $json = preg_replace("/([a-z]+)(:)/", '"$1"$2"', $json);
    $json = str_replace('}', '"}', $json);

    // echo $json; // This string is now in decodable json format
    $arr = json_decode($json, true);
    var_dump($arr);
    return;
?>

Upvotes: 1

user1299518
user1299518

Reputation:

This xml doesn't seem a valid one. It doesn't contain any DTD for the data rules or even the standard <?xml.. tags, like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
...

It contains also javascript code. SimpleXML cannot parse it either (empty array).

If you can call the javascript that it holds, do this:

$data = file_get_contents("http://meteo.arso.gov.si/uploads/probase/www/plus/timeline/timeline_radar_si_short.xml");
$data = str_replace(array('<?xml version="1.0" encoding="utf-8"?><pujs><![CDATA[',']]></pujs>'),"",$data);
echo '<script type="text/javascript">'.$data."</script>";

Upvotes: 0

Suchit kumar
Suchit kumar

Reputation: 11859

use :

$xml=simplexml_load_file("http://meteo.arso.gov.si/uploads/probase/www/plus/timeline/timeline_radar_si_short.xml");

do not use json_decode.

Upvotes: 0

Related Questions