tags:

views:

72

answers:

1

I have a root XML node called and I am trying to add a new child called to this but I am getting errors. Inside there is also children. Here is my code:

    $xml = new DomDocument();
    $xml->load(X_ASSETS);
    $xml->formatOutput = true;
    $new_id = $this->getNewAssetId();
    // Root
    $xpath = new DOMXPath($xml);
    $assets = $xpath->query('assets');
    $xml_assets = $assets->item(0);
    $xml_root = $xml->createElement('asset');
    // Asset Name
    $xml_name = $xml->createElement('name');
    $xml_name->nodeValue = $clean_name;
    $xml_root->appendChild($xml_name);
    // Asset URL
    $xml_url = $xml->createElement('url');
    $xml_url->nodeValue = '/'.$name;
    $xml_root->appendChild($xml_url);
    // Asset ID
    $xml_id = $xml->createElement('id');
    $xml_id->nodeValue = $new_id;
    $xml_root->appendChild($xml_id);


    // Create our document and save
    $xml_assets->appendChild($xml_root);
    $xml->save(X_ASSETS);

I get the following error when running this:

Fatal error: Call to a member function appendChild() on a non-object in /home/websites/zed_x/core/includes/x.inc on line 88

Does anyone know what I am doing wrong here?

+2  A: 

Somehow your $xml_assets is not an object, and therefore you cannot call the function:

$xml_assets->appendChild($xml_root);

Are you certain positive that the following command returns an object?

$xml_assets = $assets->item(0);

Test it:

if(is_object($xml_assets))
{
    echo "Object Here!";
}

This might be a good way to structure your code so you can catch errors

// .... stuff .....
$xml_assets = $assets->item(0);

// ... more stuff ....

// Check for Object
if(!is_object($xml_assests))
{
     die("No Object Created!");
}

$xml_assets->appendChild($xml_root);
$xml->save(X_ASSETS);

// .... more stuff .....
Chacha102
Oops, wrong variable.
Chacha102
Yes, it is an object, I tested it. Maybe $xml_assets is not?
Nic Hubbard
Updated it. Yeah, it would be a problem with `$xml_assets`
Chacha102
Yeah, $xml_assets is not an object...not sure why.
Nic Hubbard
+1 for suggesting to add checks at each step
Mirko Nasato
I ended up using $xml->documentElement to get the root element. Which was what I was after.
Nic Hubbard