0

i've got following example xml:

<entity id="1">
    <name>computer</name>
    <type>category</type>
    <entities>
        <entity id="2">
            <name>mac</name>
            <type>category</type>
        </entity>
        <entity id="3">
            <name>linux</name>
            <type>category</type>
            <entities>
                <entity id="4">
                    <name>ubuntu</name>
                    <type>category</type>
                </entity>
                <entity id="5">
                    <name>redhat</name>
                    <type>category</type>
                    <entities>
                        <entity id="6">
                            <name>server</name>
                            <type>category</type>
                        </entity>
                        <entity id="7">
                            <name>desktop</name>
                            <type>category</type>
                        </entity>
                    </entities>
                </entity>
            </entities>
        </entity>
    </entities>
</entity>

if i've got an id, lets say 5. is it possible to retrieve the following:

  • the name of the entity with the id=5 (redhat)
  • ALL the child entities and their id and name (6:server and 7:desktop)
  • all the parent entities and their id and name (1:computer, 2:mac and 3:linux)

im a noob on parsing xml. is this accomplished by xpath only or xquery/xpath?

i would appreciate if someone could give me some example code to do this with simplexml.

thanks!

1
  • You can use the DOM. Refer to this link. Commented Mar 17, 2010 at 6:14

2 Answers 2

1
<?php
$simpleXml = simplexml_load_string($xml); // or load your file, whatever

if (($element = $simpleXml->xpath('//*[@id = 5]'))) {
    var_dump($element);
    echo 'Element and descendants: ', $element[0]->asXML(), PHP_EOL;
    echo 'Name of the entity: ', $element[0]->name, PHP_EOL;
}

SimpleXML offers really intuitive XML processing, but it is more limited than the full DOM classes.

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

Comments

1

you can use SimpleXML.

1 Comment

so simplexml with xpath, not xquery?

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.