从SimpeXML转换时压缩数组

时间:2019-03-11 09:13:32

标签: php arrays simplexml

我具有以下XML结构:

<?xml version="1.0" encoding="UTF-8"?>
<phonebooks>
    <phonebook owner="0" name="phonebook">
        <contact>
            <person>
                <realName>Name, Firstname</realName>
            </person>
            <telephony>
                <number type="mobile" vanity="CRUSH" quickdial="7" prio="1">01751234567</number>
                <number type="work" vanity="" prio="0">02239876543</number>
                <number type="fax_work" vanity="" prio="0">02239876599</number>
            </telephony>
        <contact>
            ...
        </contact>
        ...
    </phonebook>
</phonebooks>

我尝试使用以下代码...

foreach ($xml->phonebook->contact as $contact) {
    foreach ($contact->telephony->number as $number) {
        $attributes[(string)$number] = json_decode(json_encode((array) $number->attributes()), 1);
    }
}

为我提供了有用的结果:

Array
(
    [01751234567] => Array
        (
            [@attributes] => Array
                (
                    [type] => mobile
                    [quickdial] => 7
                    [vanity] => CRUSH
                    [prio] => 1
                )
        )
     ...
)

...但是我希望结构更简单。 有没有人向我表明如何轻松消除不必要的结构层次[@attributes]? 谢谢

1 个答案:

答案 0 :(得分:1)

而不是转换为JSON并返回:

json_decode(json_encode((array) $number->attributes()), 1)

查看对象,然后将每个对象直接转换为字符串:

$attributesForThisNumber = [];
foreach ( $number->attributes() as $attrName => $attrObj ) {
    $attributesForThisNumber[] = (string)$attrObj;
}
$attributes[(string)$number] = $attributesForThisNumber;

您可以使用以下方法使它更紧凑(但不一定更具可读性):

  • iterator_to_array得到对象foreach的简单数组(没有@attributes标记)
  • array_map代替foreach
  • strval()代替(string)的字符串

给予:

$attributes[(string)$number] = array_map('strval', iterator_to_array($number->attributes()));