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

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

1 Comment

@michi: Just FYI: PHP 5.4 is without list(): $value = $property->xpath('following-sibling::value[1]')[0]; ;) + thx
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

5 Comments

I agree (+1), but why not just drop $count=count($prop)-1; & do for ($i=0;$i<$count;$i++) ?
@Wrikken ah, wait a minute, your codesample doesn't make sense, because $count isn't set. if count()is executed with every iteration --> performance
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 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...
Just the -1 to have <= instead of < struck me as curious ;)

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.