使用php从xml的一部分创建JSON

时间:2017-09-15 11:54:40

标签: php json xml

我目前正在尝试使用php解析xml文档。一切都很顺利。这是我的xml示例:

<properties>
  <property>
    <propertyid>1</propertyid>
    <flags>
      <flag>This is a flag</flag>
      <flag>This is another flag</flag>
      <flag>This is yet another flag</flag>
      <flag>etc...</flag>
    </flags>
  </property>
  <property>
    ...
  </property>
<properties>

正如您所看到的,有多个<property>个节点。我正在使用SimpleXML,它工作得很好。我只是使用php遍历每个<property>并获取值,例如:

foreach ( $xml->$property as $property )
{
  echo $property->propertyid;
}

问题是<flag>个节点。基本上,我想最终使用看起来像这样的JSON:

{
  "flags1":
  {
    "flag": "This is a flag"
  },
  "flags2":
  {
    "flag": "This is another flag"
  },
  "flags3":
  {
    "flag": "This is yet another flag"
  }
  ,
  "flags4":
  {
    "flag": "..."
  }
}

每个属性都会有不确定数量的标记。我已经尝试了一个foreach循环来获取有效的标志值,但是我如何才能获得看起来像示例JSON的值?

我的foreach循环如下所示:

$flags = $property->flags;
foreach ( $flags->flag as $index => $flag )
{
  $arr = array($index => (string)$flag);
  echo json_encode($arr);
}

返回:

{"flag":"This is a flag"}{"flag":"This is another flag"}{"flag":"This is yet another flag"}{"flag":"etc..."}

这几乎就在那里,我只是不知道如何让它变得正确。

2 个答案:

答案 0 :(得分:1)

希望这个会有所帮助。我们在这里使用simplexml_load_string

Try this code snippet here

$result=array();
$counter=0;
$xml=simplexml_load_string($string);
foreach($xml->property as $data)//iterating over properties
{
    foreach($data->flags->flag as $flag)//iterating over flag
    {
        $result["flag$counter"]=array("flag"=>(string)$flag);
        $counter++;
    }
}

print_r(json_encode($result,JSON_PRETTY_PRINT));

答案 1 :(得分:0)

{
"properties": {
    "parsererror": {
        "-style": "display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black",
        "h3": [
            "This page contains the following errors:",
            "Below is a rendering of the page up to the first error."
        ],
        "div": {
            "-style": "font-family:monospace;font-size:12px",
            "#text": "error on line 14 at column 13: Extra content at the end of the document"
        }
    },
    "property": [{
        "propertyid": "1",
        "flags": {
            "flag": [
                "This is a flag",
                "This is another flag",
                "This is yet another flag",
                "etc..."
            ]
        }
    }]
}

}