I have Xml file like
<tag>
<item>
<id>106</id>
<title>DG</title>
</item>
<item>
<id>105</id>
<title>AC</title>
</item>
</tag>
How to put each item id and title tags names to separate array
<?php
$xml = '<tag>
<item>
<id>106</id>
<title>DG</title>
</item>
<item>
<id>105</id>
<title>AC</title>
</item>
</tag>';
$dom = new DomDocument();
// $dom->load('xml.xml');
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$ExTagsArr = array();
foreach ($xpath->evaluate('//item/*') as $i=>$ExTagArr) {
$ExTagsArr[]=$ExTagArr->nodeName;
print_r($ExTagsArr);
}
i got strange arrays
Array ( [0] => id ) Array ( [0] => id [1] => title ) Array ( [0] => id [1] => title [2] => id ) Array ( [0] => id [1] => title [2] => id [3] => title )
but i need get only
Array
(
[0] => id
[1] => title
)
Array
(
[0] => id
[1] => title
)
<?php
$xml = '
<tag>
<item>
<id>106</id>
<title>DG</title>
</item>
<item>
<id>105</id>
<title>AC</title>
</item>
</tag>
';
$dom = new DomDocument();
$dom->loadXML($xml);
// Using SimpleXML
$root = simplexml_import_dom($dom);
foreach ($root->xpath('//item') as $item) {
$a = (array) $item;
var_dump($a);
}
// Using plain DOM
foreach ($dom->getElementsByTagName('item') as $item) {
$a = array();
for ($i = 0; $i < $item->childNodes->length; ++$i) {
$child = $item->childNodes->item($i);
if ($child->nodeType == XML_ELEMENT_NODE) {
$a[$child->tagName] = $child->nodeValue;
}
}
var_dump($a);
}
Also take a look at this answer.