PHP and XML error

Hi guys, ok I’m going through this book called “Learning PHP Data Objects”. Just saying so there’s a reference. Anyway I’m getting the following error when I upload the code below. The page is saved as books.xm.php. Can anyone help me?

Thanks

This page contains the following errors:

error on line 2 at column 1: Extra content at the end of the document

Below is a rendering of the page up to the first error.


<?php
/*
 * this page lists all of the books we have as an XML data structure
 * PDO LibraryManagement example application
 * @author Dennis Popel
*/

// don't forget the include
include('common.inc.php');
// set the content type to be XML
header('Content-Type: application/xml');
// get the books list
$books = Model::getBooksWithAuthors();

// echo XML declaration and open rot element
echo '<?xml version="1.0"?>', "\
";
echo "<books>\
";

// now iterate over every book and display it
while($b = $books->fetch()){

 ?>
 
 <book id="<?=$b->id?>">
  <isbn><?=$b->isbn?></isbn>
  <title><?=htmlspecialchars($b->title)?></title>
  <publisher><?=htmlspecialchars($b->publisher)?></publisher>
  <summary><?=htmlspecialchars($b->summary)?></summary>
  <author>
   <id><?=$b->author?></id>
   <lastName><?=$b->lastName?></lastName>
   <firstName><?=$b->firstName?></firstName>
  </author>
 </book>
 
 <?php
 
} // end while($b = $books->fetch()){} loop

echo '</books>';

?>

I’m kind of surprised you’re not getting “headers already sent” errors.

(BTW you showed code, not the output)

I know it makes the code easier to read with empty lines, but try removing the first couple.

The page outputs

This page contains the following errors:

error on line 2 at column 1: Extra content at the end of the document

Below is a rendering of the page up to the first error.

Forgive my posting as I’m learning php myself. But in that last loop, you have a lot of constructs that are basically <?=htmlspecialchars($var)?> - is that an alternate method of embedding php within html, or a lot of typos? I’d have done it as


<?php echo htmlspecialchars($var); ?>

  • is that just a longer way of doing the same thing or related to the PDO library being used?

Those are “short tags”. They work OK as long as PHP is configured with them enabled. I’ve never used them as having “echo” doesn’t add that much more verbosity and the code will still work if short tags are not enabled.

Maybe looking at view-source would show something helpful?

And instead of the sequential “echos” maybe string concatenation with a single echo would work?
eg.
instead of
echo “<tag>”;
try
$xml_string .= “<tag>”;

echo $xml_string;

Ah, thanks for that. I did a quick search but it confused Google. Back to topic everyone.