Writing xml with php

944

I don't know where my error comes from, i am new to xml and i need some help. I want to write an xml file using php. I have the following php code:

<?php 
 $xml = array(); 
 $xml [] = array( 
 'error' => 'ERROR_ID'
  ); 

 $doc = new DOMDocument(); 
 $doc->formatOutput = true; 

 $r = $doc->createElement( "xml" ); 
 $doc->appendChild( $r ); 

 $parameters = $doc->createElement( "parameters" );    
  $error = $doc->createElement( "error" ); 
 $error->appendChild( 
 $doc->createTextNode( $xml['error'] ) 
 ); 
 $parameters->appendChild( $error ); 


 $r->appendChild( $parameters ); 


 echo $doc->saveXML(); 
 $doc->save("write.xml") 
 ?>

My xml file should look like this:

<?xml version="1.0"?>
<xml>
  <parameters>
    <error>ERROR_ID</error>
  </parameters>
</xml>

but the ERROR_ID text node doesn't show up in the file.What went wrong?

960

Answer

Solution:

First option: replace this line:

$doc->createTextNode( $xml['error'] ) 

With this one:

$doc->createTextNode( $xml [0] ['error'] ) 

Second option: replace this line:

$xml [] = array( 

With this one: (and remove the first line)

$xml = array( 

People are also looking for solutions to the problem: php - Get first value of comma separated string

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.