PHP从xml文件解析json

问题描述:

我有点熟悉xml和json解析,但是Im对这个站点有问题。我试过PHP从xml文件解析json

$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); 

但它不起作用。当我分析数据时,我发现json中有一些javascript变量在javascript运行时转为数据,所以也许这就是为什么它不起作用。不知道如何解决它。

我想要做的是将值“9:10 CEST”...和“si0_20140930-0710_zm_si.jpg”...解析为php数组。

+1

它是XML而不是你试图解码的JSON。使用'simplexml'来代替。 – 2014-09-30 10:39:27

+0

文件是xml。那么,为什么你使用json_decode()? – Khushboo 2014-09-30 10:39:35

+0

不适用于xml eather – Jakadinho 2014-09-30 10:43:56

以下解决方案的工作。不知道是否有更好的方法来做到这一点:

<?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; 
?> 
+0

这就是我一直在寻找...我修改了一下,现在是完美的!谢谢。 – Jakadinho 2014-10-01 11:13:43

使用:

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

不使用json_decode

+0

我试过$ url = file_get_contents(“http://meteo.arso.gov.si/uploads/probase/www/plus/timeline/timeline_radar_si_short.xml”); $ xml = simplexml_load_string($ url); print_r($ xml);但它不起作用。它给了我SimpleXMLElement对象() – Jakadinho 2014-09-30 10:47:38

这个xml似乎不是一个有效的。 它不包含任何DTD对数据的规则,甚至标准<?xml..标签,就像这样:

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

它还包含的JavaScript代码。 SimpleXML无法解析它(空数组)。

如果你可以调用它持有的JavaScript,这样做:

$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>";