PDA

View Full Version : PHP4 and XML: Small Problem


cyb0rg51
09-28-2005, 01:49 PM
This code works on my own computer, but when applied to my webserver it gives me the error, "Call to a member function on a non-object on line 16".

I am assuming that when tested on my computer with PHP >=4.3 the variable $image is treated as an oject. However when applied to my webserver with PHP 4.3.11 the variable $image seems to be treated as an array?? Any help at all would be great.
<?php
//loads the XML file

$xmlPath = dirname(__FILE__) . "/";
$xmldoc = domxml_open_file($xmlPath . "gallery_tree.xml");

//Set root node "tree"
$root = $xmldoc -> document_element();

//Gets all the "image"s
$images = $xmldoc -> get_elements_by_tagname("image");
foreach($images as $image)

//The newly created node
$mynode = $xmldoc -> create_element("image");
$mynode -> set_attribute("label", "label test");
$mynode -> set_attribute("src", "location test");

//Assign Parent Node (folder)
$parent = $image -> parent_node();
$parent -> append_child($mynode);

echo $xmldoc -> dump_mem();
?>

Sidelong
09-28-2005, 02:57 PM
Hi,

Perhaps this was just a typo from your side, but you are missing {} braces after your foreach statement.

As it stands your code will execute only the first line:

foreach ($images as $image)
... (first line)

so by the time you reference the $image variable, the PHP engine has no idea what you mean.

Change the above to :

foreach ($images as $image) {
.. line 1
.. line 2
...
... line n
}


Hope that helps!

Fou-Lu
09-28-2005, 04:02 PM
The foreach is definitly a problem, but I'm more interested in your object->array values. When I use my 4.3.8, such a request would also return my $image as an array, not as an object. Part of it is due to the DomDocument request as opposed to the DomElement request. But, if your code is identical on two (assuming apache) systems, with the same XML file to read, theres only two things I can think of that may alter these values. The first is one of the systems has an inacurrate setup for the default mode of the domxml_open_file, which is including dont_keep_blanks (or whatever its called), or (and this one seems more likely), your libxml versions are different. Considering that DOMXML is an addon function to php, it is possible that there could be a differencial between these two; personally I consider it odd to change the core usage for it, but that doesn't mean it hadn't been done.
Its a pitty that you don't have the 5.x version for the DOM, its far better than the DOMXML, and is fully OOP as opposed to the hit-and-miss DOMXML version.

Recursive functions can be of good use with XML applications as well, sometimes you do not know what it contains and you can evaluate to an object from an array with this method. But it all depends on what you have, and what you want it to be.