-1

I got an XML-File that Looks like this:

    <?XML version="1.0" encoding="UTF-8"?>
    <test:start xmlns:test="http://www.test.de" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <test:uebertragung art="OFFLINE" version="1.0.0"></test:uebertragung>
    <test:object>
            <test:objectnr>5</test:objectnr>
            <test:objectview>
                    <test:geo>
                            <test:lat>12</test:lat>
                            <test:long>30</test:long>
                    </test:geo>
                    <test:objectcategorie>5</test:objectcategorie>
                    <test:geo>
                            <test:lat>11</test:lat>
                            <test:long>30</test:long>
                    </test:geo>
                    <test:objectcategorie>8</test:objectcategorie>
                    <test:geo>
                            <test:lat>16</test:lat>
                            <test:long>30</test:long>
                    </test:geo>
                    <test:objectcategorie>2</test:objectcategorie>
                    <test:geo>
                            <test:lat>14</test:lat>
                            <test:long>35</test:long>
                    </test:geo>
                    <test:objectcategorie>14</test:objectcategorie>
            </test:objectview>
    </test:object>
    </test:start> 

Now I want to parse this file in php. I got the following code which show me only the first object:

$xmlDoc->load("test.xml");
$x = $xmlDoc->documentElement;
$x = $x->childNodes[1];
$x = $x->childNodes[1];
foreach ($x->childNodes AS $item) {
    print $item->nodeName . " = " . $item->nodeValue . "<br>";
}

Can somebody explain me a easier way to parse this XML-File. I want to show only the "test:lat" from all "objectsviews" and the "objectcategorie".

1 Answers1

0

Hopefully this will be of use to you to solve your issue.

    libxml_use_internal_errors( TRUE );

    $dom = new DOMDocument('1.0','utf-8');
    $dom->validateOnParse=false;
    $dom->standalone=true;
    $dom->strictErrorChecking=false;
    $dom->recover=true;
    $dom->load( 'test.xml' );

    libxml_clear_errors();


    $xpath=new DOMXPath( $dom );
    $rns = $dom->lookupNamespaceUri( $dom->namespaceURI ); 
    $xpath->registerNamespace( 'test', $rns );

    $col = $xpath->query('//test:geo');
    foreach( $col as $node ) {
        foreach( $node->childNodes as $cn ){
            if( is_object( $cn ) && $cn->nodeType==1 ) echo $cn->tagName.'='.$cn->nodeValue.'<br />';   
        }
    }

    $dom=$xpath=$rns=$col=null;

/*
    This outputs:
    -------------
    test:lat=12
    test:long=30
    test:lat=11
    test:long=30
    test:lat=16
    test:long=30
    test:lat=14
    test:long=35
*/
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46