[php] domxml parse probleem

Pagina: 1
Acties:

Onderwerpen


Acties:
  • 0 Henk 'm!

Anoniem: 129063

Topicstarter
Hoi,

Ik wil met de DOMXML functies van PHP4 een xml file parsen, maar ik kom er niet helemaal uit.
De XML layout is als volgt:
code:
1
2
3
4
5
6
7
8
<bedrijf>
  <stats total="3">
    <record id="1" tag1="blabla1" bedrag="2" bedrag2="3" /> 
    <record id="2" tag1="blabla2" bedrag="2" bedrag2="3" /> 
    <record id="3" tag1="blabla3" bedrag="2" bedrag2="3" /> 
  </stats>
  <totaal bedrag="8" bedrag2="10" /> 
</bedrijf>

Ik wil eigenlijk alleen de waarde van de "tag1"-attributes hebben (blabla1, blabla2 en blabla3)

code:
1
2
3
4
5
6
7
8
9
10
11
if (!$xmldoc = domxml_open_file()) {
    echo "Error while parsing the document\n";
    exit;
}
$dom = $xmldoc->document_element();
$children = $dom->child_nodes();
$stats = $children[1];
$stats_children = $stats->child_nodes();
echo "<pre>\n";
print_r($stats_children[0]->name);
echo "</pre>\n";

...dit geeft alleen "#text" als resultaat...

Hoe doe je dit op de goede manier?
Met de documentatie en de code comments op php.net kom ik er niet uit.

Alvast bedankt!

[ Voor 6% gewijzigd door Anoniem: 129063 op 02-10-2006 12:46 ]


Acties:
  • 0 Henk 'm!

  • NMe
  • Registratie: Februari 2004
  • Laatst online: 11-06 00:38

NMe

Quia Ego Sic Dico.

Ik doe weinig met XML, maar is de eerste childnode van <stats> niet een tekst met daarin allemaal whitespace? Moet je niet $stats_children[1]->name hebben op regel 10?

'E's fighting in there!' he stuttered, grabbing the captain's arm.
'All by himself?' said the captain.
'No, with everyone!' shouted Nobby, hopping from one foot to the other.


Acties:
  • 0 Henk 'm!

Anoniem: 183031

Je hebt nooit de garantie dat het eerste element ook daadwerkelijk het element "stats" bevat. Dit moet je dus controleren (evenals alle andere elementen en attributen). Je krijgt dus zoiets als dit:

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
if (!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

// Get the root element
$root = $dom->document_element();

// Chech if the root has any child nodes
if($root->has_child_nodes()) {
  // Get the child nodes
  $children = $root->child_nodes();
  // Find the stats element
  foreach($children as $node) {
    if(($node->node_type() == XML_ELEMENT_NODE) && ($node->node_name() == "stats")) {
      // Stats element
      // Get the child nodes
      $children2 = $node->child_nodes();
      // Find the record element
      foreach($children2 as $node2) {
        if(($node2->node_type() == XML_ELEMENT_NODE) && ($node2->node_name() == "record")) {
          // Record element
          // Get the attribute
          if($node2->has_attributes()) {
            // Node has attributes, get them
            $attributes = $node2->attributes();
            
            echo $attributes["tag1"];
          }
        }
      }
    }
  }
}