I used a Class to parse an XML-file. The XML-file looks like that:
<?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. 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.
<?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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.