Reputation: 37
PHP array to XML problem. I have an array and when trying to convert it into an xml file, it is counting the total fields using "item0" "item1"...so on. I only want it to display "item" "item". Examples below. Thank you.
PHP code turning the array($store) into an XML file.
// initializing or creating array
$student_info = array($store);
// creating object of SimpleXMLElement
$xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><student_info></student_info>");
// function call to convert array to xml
array_to_xml($student_info,$xml_student_info);
//saving generated xml file
$xml_student_info->asXML('xmltest.xml');
// function defination to convert array to xml
function array_to_xml($student_info, &$xml_student_info) {
foreach($student_info as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_student_info->addChild("$key");
array_to_xml($value, $subnode);
}
else{
$subnode = $xml_student_info->addChild("item$key");
array_to_xml($value, $subnode);
}
}
else {
$xml_student_info->addChild("$key","$value");
}
}
}
What the XML file looks like (with the item# error)
<student_info>
<item0>
<item0>
<bus_id>2436</bus_id>
<user1>25</user1>
<status>2</status>
</item0>
<item1>
<bus_id>2438</bus_id>
<user1>1</user1>
<status>2</status>
</item1>
<item2>
<bus_id>2435</bus_id>
<user1>1</user1>
<status>2</status>
</item2>
</item0>
</student_info>
Once again, I just want each "item" to display "item" with no number. and the first and last "item0"... I dont know what thats about. Thanks for any help!
Upvotes: 1
Views: 674
Reputation: 18933
Replace this:
else{
$subnode = $xml_student_info->addChild("item$key");
array_to_xml($value, $subnode);
}
with this:
else{
$subnode = $xml_student_info->addChild("item");
array_to_xml($value, $subnode);
}
I don't know how your array is structured but, from the output, I would guess the problem is in the following line:
$student_info = array($store);
So, change to this:
if (!is_array($store)) {
$student_info = array($store);
} else {
$student_info = $store;
}
This should fix it
Upvotes: 3