0

I have an XML like this:

<properties>
  <property>name</property><value>john</value>
  <property>surname</property><value>wayne</value>
  <property>age</property><value>33</value>
  <property>blaaa</property><value>blaa</value>
</properties>

I have to parse this and I used something like this:

$xle = simplexml_load_file('xml.xml');
foreach ($xle->properties as $properties) {
    foreach ($properties->property as $property) {
        echo $property, "<br />\n";
    }
    foreach ($properties->value as $value) {
        echo $value, "<br />\n";
    }
}

I came to this so far, i need something like

"property = value" "name = john"

my code outputs something like this :

name
surname
age
blaa
john
wayne
33
blaa
hakre
  • 193,403
  • 52
  • 435
  • 836

2 Answers2

2

Each value is a following sibling to the property element. You can express that with xpath quite easily:

following-sibling::value[1]

will give you the <value> element if the <property> element is the context-node.

Getting the context-node with SimpleXML is rather straight forward, so here is the example PHP code:

$properties = simplexml_load_file('xml.xml');

foreach($properties->property as $property)
{
    list($value) = $property->xpath('following-sibling::value[1]');
    echo $property, " = ", $value, "\n";
}

The output for the example XML then is:

name = john
surname = wayne
age = 33
blaaa = blaa

Online Demo

This looks similar to a properties file (plist) for which I know of a related Q&A from memory, so it's maybe interesting as well to you:

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • 1
    @michi: Just FYI: PHP 5.4 is without `list()`: `$value = $property->xpath('following-sibling::value[1]')[0];` ;) + thx – hakre Mar 12 '13 at 22:55
1

I agree, a weird format, but valid. Given that every <property> is followed by its <value>, go...

$xml = simplexml_load_file('xmlfile.xml');

$prop = $xml->xpath('//property');
$value = $xml->xpath('//value');

$count=count($prop)-1;

for ($i=0;$i<=$count;$i++) {
    echo $prop[$i].": ".$value[$i]."<br />";;
}  

---> live demo: http://3v4l.org/0CS73

michi
  • 6,565
  • 4
  • 33
  • 56
  • I agree (+1), but why not just drop `$count=count($prop)-1;` & do `for ($i=0;$i<$count;$i++)` ? – Wrikken Mar 12 '13 at 21:35
  • @Wrikken ah, wait a minute, your codesample doesn't make sense, because `$count` isn't set. if `count()`is executed with every iteration --> performance – michi Mar 12 '13 at 21:37
  • Erm, sorry, I meant `$count=count($prop)` & `foreach($i=0;$i<$count;$i++)`, my apologies. You are of course totally correct of not having `count()` in the `for`. – Wrikken Mar 12 '13 at 21:38
  • @Wrikken no problem. I guess if the xml has just a few nodes, like in his example, performance is ok with `count()` in the loop. a real big xml though... – michi Mar 12 '13 at 21:40
  • 1
    Just the `-1` to have `<=` instead of `<` struck me as curious ;) – Wrikken Mar 12 '13 at 21:41