2017-09-15 59 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..." 
      ] 
     } 
    }] 
} 

}