javsmo
javsmo

Reputation: 1337

Get next element with PHP SimpleXML

I received a very weird XML file to process.

Instead of grouping names with group tags, like this:

<data>
    <group>
        <name>John</name>
        <name>Mary</name>
        <name>Susan</name>
    </group>
    <group>
        <name>Cesar</name>
        <name>Joseph</name>
        <name>Sylvia</name>
        <name>Steve</name>
    </group>
</data>

It inserts a separator tag after each element, like this:

<data>
    <name>John</name>
    <separator>,</separator>
    <name>Mary</name>
    <separator>,</separator>
    <name>Susan</name>
    <separator>;</separator>
    <name>Cesar</name>
    <separator>,</separator>
    <name>Joseph</name>
    <separator>,</separator>
    <name>Sylvia</name>
    <separator>,</separator>
    <name>Steve</name>
    <separator>.</separator>
</data>

";" and "." are the group delimiters. (I know, that's weird, but I can't change that and I have to process a lot of these files)

To get all names and all separators I can use the following code:

$data = <<<XML
    <data>
        <name>John</name>
        <separator>,</separator>
        <name>Mary</name>
        <separator>,</separator>
        <name>Susan</name>
        <separator>;</separator>
        <name>Cesar</name>
        <separator>,</separator>
        <name>Joseph</name>
        <separator>,</separator>
        <name>Sylvia</name>
        <separator>,</separator>
        <name>Steve</name>
        <separator>.</separator>
    </data>
XML;

$xml = simplexml_load_string($data);

foreach ($xml->name as $name){
    echo "$name\n";
}

foreach ($xml->separator as $sep){
    echo "$sep\n";
}

But this way, I can't get the name and the correspondent separator on a single loop.

Is there any way to know, on the first loop, the next element of each name?

Upvotes: 3

Views: 1059

Answers (2)

michi
michi

Reputation: 6625

Parse the XML like this and build an array:

$xml = simplexml_load_string($x);

foreach ($xml->children() as $name => $value) {

    if ($name == 'name') $names[$i][] = (string)$value;
    elseif ($name == 'separator' && $value == ';') $i++;

}

Output $names:

array(2) {
  [0]=>array(3) {
    [0]=>string(4) "John"
    [1]=>string(4) "Mary"
    [2]=>string(5) "Susan"
  }
  [1]=>array(4) {
    [0]=>string(5) "Cesar"
    [1]=>string(6) "Joseph"
    [2]=>string(6) "Sylvia"
    [3]=>string(5) "Steve"
  }
}

You can then just pick the names from the array.

see it working: https://eval.in/95853

Upvotes: 2

Barış &#199;ELİK
Barış &#199;ELİK

Reputation: 49

I hope that i understand your question.

$xml = simplexml_load_string($data);
$i = 0;
$res = '';
foreach ($xml->name as $name){
    $res .= "$name ".$xml->separator[$i];
    $i++;
}
$groups = explode(';',$res);

Upvotes: 3

Related Questions