简体   繁体   中英

how to change xml tag to pascal case in php

<?php
function array_to_xml(array $arr, SimpleXMLElement $xml)
{
    foreach ($arr as $k => $v) {
        is_array($v)
            ? ucwords(array_to_xml($v, $xml->addChild($k)))
            : ucwords($xml->addChild($k, $v));
    }
    return $xml;
}

$test_array = array (
  'blaPo' => '1',
  'Items' => '1',
    'another_array' => array (
        'stack' => 'overflow',
    ),
);

echo array_to_xml($test_array, new SimpleXMLElement('<root/>'))->asXML();

I want to change Tag name to Pascal case i used ucwords too its not working in the server

When you are using ucwords() you are both doing it on a SimpleXMLElement, but also your not storing the value returned...

is_array($v)
    ? ucwords(array_to_xml($v, $xml->addChild($k)))
    : ucwords($xml->addChild($k, $v));

Instead you should just use it when using addChild() , applying it to the name of the element being created

is_array($v)
    ? array_to_xml($v, $xml->addChild(ucwords($k)))
    : $xml->addChild(ucwords($k), $v);

Which with your test data gives...

<?xml version="1.0"?>
<root><BlaPo>1</BlaPo><Items>1</Items><Another_array><Stack>overflow</Stack></Another_array></root>

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.

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