开发者

PHP: Displaying Dom object and Creating xml file

<?php                                               

  $books = array();
  $books [] = array(
  'title' => 'PHP Hacks',
  'author' => 'Jack Herrington',
  'publisher' => "O'Reilly"     
  );                            
  $books [] = array(            
  'title' => 'Podcasting Hacks',
  'author' => 'Jack Herrington',
  'publisher' => "O'Reilly"     
  );                            

  $doc = new DOMDocument();     
  $doc->formatOutput = true;    
  $r = $doc->createElement( "books" );
  $doc->appendChild( $r );            
  foreach( $books as $book )          
  {                                   
  $b = $doc->createElement( "book" ); 

  $author = $doc->createElement( "author" );
  $author->appendChild(
  $doc->createTextNode( $book['author'] )
  );
  #$author->appendChild( $doc->createTextNode( 'pavunkumar'));
  $new = $doc->createElement("Developer");
  $a=$doc->createTextNode('I am developer ' );
  $new->appendChild($a);
  $b->appendChild( $author );
  $b->appendChild($new);
  $b->appendChild($new);
  $title = $doc->createElement( "title" );
  $title->appendChild(
  $doc->createTextNode( $book['title'] )
  );
  $b->appendChild( $title );
  $publisher = $doc->createElement( "publisher" );
  $publisher->appendChild(
  $doc->createTextNode( $book['publisher'] )
  );
  $b->appendChild( $publisher );

  $r->appendChild( $b );
  }
  echo $doc->SaveXml() ;
  ?>

When I run this code in command line. I am getting following things

<?xml version="1.0"?>
<books>
  <book>
    <author>Jack Herrington</author>
    <Developer>I am developer </Developer>
    <title>PHP Hacks</title>
    <publisher>O'Reilly</publisher>
  </book>
  <book>
    <author>Jack Herrington</author>
    <Developer>I am developer </Developer>
    <title>Podcasting Hacks</title>
    <publisher>O'Reilly</publisher>
  </book>
</books>

When I run the code in web browser it gives me following things

Jack Herrington  I am developer  O'Reilly    Jack Herrington  I am developer  O'Reilly  

I want to above output to be like command line output. And one more things is that instead o开发者_如何转开发f displaying , how could I create a xml file using $doc Dom object.


I may not be correct, but try sending a header like that:

Header("Content-Type: text/xml");

or

Header("Content-Type: text/plain");

to achieve appropriate results. (Of course before you run $doc->saveXML();.


Convert < and > to entities with htmlspecialchars (http://ua.php.net/manual/en/function.htmlspecialchars.php) and browser will not parse it as html:

echo htmlspecialchars($doc->SaveXml());


It's because you are outputing XML code into PHP file (translated into HTML). Check your source code and you'll see the desired output. If you want to get the same thing as you got in command line, you'll have to save your output to new XML file.

Use fopen to create new XML file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜