2017-09-15 31 views
0

我目前正在尝试用php解析xml文档。除了一件事之外,一切都进展顺利。以下是我的xml示例:从PHP的部分XML创建JSON

<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,它工作得很好。我只是通过每个<property>用PHP循环,得到的值,例如:

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..."} 

这等近那里,我只是不知道如何得到它是正确的。

回答

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

谢谢你,这是完美的:) – DesignSubway

+1

@DesignSubway很乐意帮助你的朋友... :) –

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..." 
      ] 
     } 
    }] 
} 

}