【问题标题】:Create JSON from part of xml with php使用 php 从部分 xml 创建 JSON
【发布时间】:2017-09-15 11:54:40
【问题描述】:

我目前正在尝试使用 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>

如您所见,有多个 &lt;property&gt; 节点。我正在使用 SimpleXML,它工作得很好。我只是用 php 遍历每个 &lt;property&gt; 并获取值,例如:

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

问题在于&lt;flag&gt; 节点。基本上,我希望得到如下所示的 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..."}

这已经差不多了,我只是不知道如何让它正确。

【问题讨论】:

    标签: php json xml


    【解决方案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));
    

    【讨论】:

    • 谢谢你,这是完美的:)
    • @DesignSubway 很高兴帮助你的朋友... :)
    【解决方案2】:
    {
    "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..."
                ]
            }
        }]
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多