0

EDITED
I'm trying to put my form inputs into an xml file.

Searching on this site I've found the following code and I used it to parse $_POST content.

After a few attempts I realized that "numeric tags" (resulting from not-associative arrays) could be reason of my insuccess so I modified the code as below:

function array_to_xml(array $arr, SimpleXMLElement $xml, $NumK = false)
{
    foreach ($arr as $k => $v) {
        if (is_array($v)){
            preg_match('/^0|[1-9]\d*$/', implode(array_keys($v)))
            ? array_to_xml($v, $xml->addChild($k), true)
            : array_to_xml($v, $xml->addChild($k));
        }else{
            $NumK
            ? $xml->addChild('_'.$k.'_', $v)
            : $xml->addChild($k, $v);
        }
    }
    return $xml;
}

Anyway I'm still "fighting" with xpath commands because I'm not able to find the GrandParent of some nodes (coming from not-associative arrays) that I need to convert into repeated tags.

That's the logic I'm trying to follow:
1st - Find nodes to reformat (The only ones having numeric tag);
2nd - Find grandparent (The tag I need to repeat);
3rd - Replace the grandparent (and his descendants) whith a grandparent's tag for each group of grandchilds (one for each child).

So far I'm still stuck on 1st step beacuse of xpath misunderstanding.

Below, the result xml I have and how I would to transform it:

My array is something like:

$TestArr = Array
    ("First" => array
        ("Martha" => "Text01"
        ,
        "Lucy" => "Text02"
        ,
        "Bob" => array 
            ("Jhon" => array
                ("01", "02")
            ),
        "Frank" => "One"
        ,
        "Jessy" => "Two"
        )
    ,
    "Second" => array
        ("Mary" => array 
            ("Jhon" => array
                ("03", "04")
            ,
            "Frank" => array
                ("Three", "Four")
            ,
            "Jessy" => array
                ("J3", "J4")
            )
        )
    );

using the function array_to_xml($TestArr, new SimpleXMLElement('<root/>')) I get an xml like:

<root>
    <First>
        <Martha>Text01</Martha>
        <Lucy>Text02</Lucy>
        <Bob>
            <Jhon>
                <_0_>01</_0_>
                <_1_>02</_1_>
            </Jhon>
        </Bob>
        <Frank>One</Frank>
        <Jessy>Two</Jessy>
    </First>
    <Second>
        <Mary>
            <Jhon>
                <_0_>03</_0_>
                <_1_>04</_1_>
            </Jhon>
            <Frank>
                <_0_>Three</_0_>
                <_1_>Four</_1_>
            </Frank>
            <Jessy>
                <_0_>J3</_0_>
                <_1_>J4</_1_>
            </Jessy>
        </Mary>
    </Second>
</root>

My needed result is something like:

<root>
    <First>
        <Martha>Text01</Martha>
        <Lucy>Text02</Lucy>
            <Bob>
                <Jhon>01</Jhon>
            </Bob>
            <Bob>
                <Jhon>02</Jhon>
            </Bob>
        <Frank>One</Frank>
        <Jessy>Two</Jessy>
    </First>
    <Second>
        <Mary>
            <Jhon>03</Jhon>
            <Frank>Three</Frank>
            <Jessy>J3</Jessy>
        </Mary>
        <Mary>
            <Jhon>04</Jhon>
            <Frank>Four</Frank>
            <Jessy>J4</Jessy>
        </Mary>
    </Second>
</root>
6
  • Have you tried this? pastebin.com/pYuXQWee Commented Jan 22, 2018 at 19:22
  • @DanielO. Sorry: same result Commented Jan 22, 2018 at 19:32
  • What about JSON, why XML? Commented Jan 22, 2018 at 19:35
  • @DanielO. Because the goal is insert some data inta an xml and send it using a specific achitecture (I mean the structure of the xml) Commented Jan 22, 2018 at 19:37
  • Ok, would it be possible to generate the XML manually? Commented Jan 22, 2018 at 19:38

2 Answers 2

3
+50

I've updated the code to try and get closer to what you were trying to achieve. I've taken into the account of how to identify the grouping of data and to do this I've added an 'id' attribute to each of the elements added in this way. Also for convenience, I set a 'max' counter for the parent elements.

The first XPath expression (//*[@id]/..) fetches all the elements that needed to be processed. This then loops for the number of sub elements counted earlier. The XPath descendant::*[@id='{$i}'] picks out each set of elements (so all ones with id='0', then '1' etc.) This is the natural grouping of the data.

function array_to_xml(array $arr, SimpleXMLElement $xml, string $elementName = null)
{
    foreach ($arr as $k => $v) {
        if (is_array($v)){
            if ( preg_match('/^0|[1-9]\d*$/', implode(array_keys($v)))) {
                array_to_xml($v, $xml, $k);
            }
            else    {
                array_to_xml($v, $xml->addChild($k));
            }
        }
        else    {
            if ( $elementName != null )   {
                $newElement = $xml->addChild($elementName, $v);
                $newElement["id"] = $k;
                $xml["max"] = $k;
            }
            else    {
                $xml->addChild($k, $v);
            }
        }
    }
    //return $xml;
}
$xml = new SimpleXMLElement("<root />");
array_to_xml($TestArr, $xml);
$todoList = $xml->xpath("//*[@id]/..");
foreach ( $todoList as $todo )  {
    $parent = $todo->xpath("..")[0];
    for ( $i = 0; $i <= $todo['max']; $i++ )    {
        $content = $todo->xpath("descendant::*[@id='{$i}']");
        $newName = $todo->getName();
        $new = $parent->addChild($newName);
        foreach ( $content as $addIn )  {
            $new->addChild($addIn->getName(), (string)$addIn);
        }
    }
    unset ( $parent->$newName[0]);
}

print $xml->asXML(); 

Outputs...

<?xml version="1.0"?>
<root>
    <First>
        <Martha>Text01</Martha>
        <Lucy>Text02</Lucy>
        <Frank>One</Frank>
        <Jessy>Two</Jessy>
        <Bob>
            <Jhon>01</Jhon>
        </Bob>
        <Bob>
            <Jhon>02</Jhon>
        </Bob>
    </First>
    <Second>
        <Mary>
            <Jhon>03</Jhon>
            <Frank>Three</Frank>
            <Jessy>J3</Jessy>
        </Mary>
        <Mary>
            <Jhon>04</Jhon>
            <Frank>Four</Frank>
            <Jessy>J4</Jessy>
        </Mary>
    </Second>
</root>
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your attempt, but the original code makes me able to find the nodes I need to replace (the only ones having numeric tag between underscores). In the xml resulting from your code it's impossible to automatically select the nodes that I need to reposition.
I've had a further play, interested if it helps any more.
I think I'm near to my goal (I'll post as answer if my checks will be ok) +1 for your attention ;) oops Sorry I didn't read carefully. I'll test it and if it works I'll give you the bonus
I get error: Catchable fatal error: Argument 3 passed to array_to_xml() must be an instance of string, string given
I did it but your code is shorter (and more professional) and your output seems what I need. If you make it works I'll give you the bouty with pleasure
0

Iterate your array value and add elements with the same key

if (is_array($v)){
    foreach($v as $arr_ele){
        $xml->addChild($k, $arr_ele);
    }
}

1 Comment

Elements are all added by the posted function. I need to reorder them as explained in my question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.