簡體   English   中英

需要幫助解析使用PHP的Flat XML

[英]Need help parsing Flat XML with PHP

我試圖解析 使用PHP以下列方式構造的XML文件時遇到了一個真正的問題。
您可能會注意到,它們是鍵 - >值對,但它可以是鍵 - >字符串鍵 - >數據等。

有人有個主意嗎? 我非常感謝你的幫助。

此外,數據來自外部接口,我無法控制它的格式。

<array>
    <dict>
        <key>name</key>
        <string>John</string>
        <key>surname</key>
        <string>Smith</string>
        <key>Car</key>
        <string>Ford</string>
        <key>picture</key>
        <data>AAAA====</data>
        <key>age</key>
        <string>32</string>
    </dict>
</array>

我想用某種方式重新格式化數據,例如:

array
  -dict
    -name=John
    -surname=smith

等等

看看simplexml類: http//php.net/simplexml

此外,XML有一個標准,因此即使您的XML來自外部接口,它們也應該是標准的有效XML。

編輯

<?php
$xmlstr = <<<XML
<array>
    <dict>
        <key>name</key>
        <string>John</string>
        <key>surname</key>
        <string>Smith</string>
        <key>Car</key>
        <string>Ford</string>
        <key>picture</key>
        <data>AAAA====</data>
        <key>age</key>
        <string>32</string>
    </dict>
</array>
XML
;

$tmp = simplexml_load_string($xmlstr);
$var = (array)$tmp->dict;
$keys = array();
foreach($tmp->dict->children() as $k => $v) {
        if($k == 'key') $key = (string)$v;
        else $keys[$key] = (string)$v;
}

print_r($keys);

怎么樣的:

$temp = new SimpleXMLElement($xml);
$array = array();
foreach($temp->dict->children() as $value) {
    if($value->getName() == 'key') {
        $key = (string)$value;
    } elseif($value->getName() == 'string') {
        $array[$key] = (string)$value;
    } elseif($value->getName() == 'data') {
        // possibly treat data differently, or maybe not
        $array[$key] = (string)$value;
    }
}

print_r($array);

它會嘗試收集鍵和值,並在它們運行時將它們分配給數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM