简体   繁体   English

解析XML文档后循环遍历关联数组

[英]Loop through an Associative Arrays after parsing an XML document

I used a Class to parse an XML-file. 我使用了一个类来解析XML文件。 The XML-file looks like that: XML文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<user>
   <name id="1">John Mal</name>
   <addr>123 N 45</addr>
   <phone id="5">555.55.222</phone>
</user>

The result of parsing is an -associative Arrays: 解析的结果是一个关联数组:

Array (
    [0] => Array (
        [name] => USER
        [content] =>
        [child] => Array(
            [0] => Array(
                [name] => NAME
                [attrs] => Array([ID] => 1)
                [content] => John Mal
            )
            [1] => Array(
                [name] => ADDR
                [content] => 123 N 45
            )
            [2] => Array(
                [name] => PHONE
                [attrs] => Array([ID] => 5)
                [content] => 555.55.222
            )
        )
    )
)

My problem is how to traverse the array and get the information inside. 我的问题是如何遍历数组并获取内部信息。 For example I want to get the first id and the content of the name -tag and so one in a separate lines because after that I want to write all the information in a text-file. 例如,我想获得第一个idname -tag的内容,因此要在单独的一行中输入,因为在此之后,我想将所有信息写入文本文件中。 How to do that? 怎么做? Any help is very appreciate. 任何帮助都非常感谢。

That parse function doesn't look particular useful for what you're trying to achieve. 该解析函数对于您要实现的目标似乎并不特别有用。
You might be interested in SimpleXML instead. 可能SimpleXML感兴趣。

<?php
$user = new SimpleXMLElement(data());
echo 'name=', $user->name,' id=', $user->name['id'], PHP_EOL;
echo 'addr=', $user->addr, PHP_EOL;
echo 'phone=', $user->phone,' id=', $user->phone['id'], PHP_EOL;



function data() {
    return <<< eox
<?xml version="1.0" encoding="utf-8"?>
<user>
   <name id="1">John Mal</name>
   <addr>123 N 45</addr>
   <phone id="5">555.55.222</phone>
</user>
eox;
}

I'd vote for a parser like DOM or SimpleXml for powerful features over an array. 我会为诸如DOMSimpleXml类的解析器投票,以获取数组上的强大功能。 If you have to use the array though... 如果您必须使用数组...

this is how to access a specific datum in your complex array directly: 这是直接访问复杂数组中特定基准的方法:

var_dump($a[0]['child'][0]['content']);

Output: 输出:

string(8) "John Mal"

Iteration: 迭代:

foreach ($a as $set) {

    echo $set['name'] . PHP_EOL;
    echo $set['content'] . PHP_EOL;
    echo "----------------" . PHP_EOL;

    foreach ($set['child'] as $item) {

        foreach ($item as $key => $value) {

            echo "$key: $value" . PHP_EOL;
        }
    }
}    

Output: 输出:

USER
CONTENT
----------------
name: NAME
attrs: Array
content: John Mal
name: ADDR
content: 123 N 45
name: PHONE
attrs: Array
content: 123.345  

see it in action and play around with it: https://eval.in/530409 在实际操作中查看并尝试使用它: https : //eval.in/530409

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM