2

I am developing an application were I need to transform XML documents that look like this(words.xml):

<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE words SYSTEM "words.dtd">
<words>
<word id="word_1">Alfa</word>
<word id="word_2">Beta</word>
<word id="word_3">Gamma</word>
<word id="word_4">Delta</word>
<word id="word_5">Zeta</word>
</words>

Using PHP5 and DOM. I would like the result to be (in this case):

word_1 = Alfa
word_2 = Beta
word_3 = Gamma
word_4 = Delta
word_5 = Zeta 

My PHP code:

<?php

$xmlHitzakDok = new DOMDocument();
$xmlHitzakDok->load("words.xml");

$x = $xmlHitzakDok->documentElement;
foreach ($x->childNodes AS $item)
  {
  print $item->nodeName . " = " . $item->nodeValue . "<br />";
  }
?>

I am getting no results. Which is the problem?

2
  • 2
    Wouldn't it be something more along the lines of "node->attribute( 'id' )" = ? Commented Apr 19, 2012 at 16:15
  • error reporting and display errors set properly? no error found? Commented Apr 19, 2012 at 16:20

1 Answer 1

3

The problem is not that $xmlHitzakDok->documentElement is not the <words> element, it's the document itself, it does not contain any data.

I suggest using xpath to get the elements you want.

$xPath = new DOMXPath($xmlHitzakDok);

foreach ($xPath->query('//words/word') AS $item)
{
    echo $item->getAttribute('id') . " = " . $item->nodeValue . "<br/>";
}
Sign up to request clarification or add additional context in comments.

10 Comments

Works for me (codepad.org/oi3XP7cm). Are you sure that words.xml exists? Try using $xmlHitzakDok->load(realpath("words.xml"));.
Or try doing if($xmlHitzakDok->load("words.xml") === FALSE){die('error loading file');} My guess is the file isn't being loaded correctly.
Hi, I did that and "error loading file" message appeared on the browser. I dont know why the file cant be loaded. "words.xml" is located on the same folder as the php, exactly in /var/www/myfolder/. Why is this? Any idea @Rocket? Thanks.
I finally solved the problem, had to change privileges to words.xml. Thanks for your time @Rocket.
@Rocket: $xmlHitzakDok->documentElement is the <words> element, you can check that with ->documentElement->tagName easily, see as well codepad.org/YdCCk4LX (just FYI)
|

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.