-2
$books = new DOMDocument();
$books->load( 'books.xml' );
$id = $_GET['id'];  
$xml = '<?xml version="1.0" encoding="UTF-8"?>'; 
$xml .= '<results><course>'.$id.'</course>'; 
$xml .= '<books>';
$items = $books->getElementsByTagName("item");
foreach( $items as $item )
{ 
    $item_id = $item->getAttribute("id");
    if($id == $item_id){
      ....
    }
}
$xml .= '</books></results>'; 
header ("Content-Type:text/xml");
echo ($xml);

My code above will return me :

<results>
   <course>1111</course>
   <books>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="248"/>
      ..... 
   </books>
</results>

This page contains the following errors:

error on line 772 at column 12: XML declaration allowed only at the start of the document Below is a rendering of the page up to the first error.

Patricia
  • 7,752
  • 4
  • 37
  • 70
user236501
  • 8,538
  • 24
  • 85
  • 119
  • Please always Google first before asking a question on Stack Overflow and thus, occupying your fellow users' time. The first result to `php sort xml` contains a full answer. Thanks! – Pekka Feb 22 '13 at 13:04
  • possible duplicate of [Sort XML via attribute value PHP](http://stackoverflow.com/questions/1359224/sort-xml-via-attribute-value-php) – Pekka Feb 22 '13 at 13:05
  • Try that solution already not working that is why post here. – user236501 Feb 22 '13 at 13:05
  • Then add that context and specify what is not working. Don't just ask a duplicate with no background info and no reference to the original. – Pekka Feb 22 '13 at 13:06
  • Seems to be an exact duplicate of http://stackoverflow.com/questions/14957449/sorting-xml-file-into-ascending-order-using-php/14960365#14960365. See my answer there. – silkfire Feb 22 '13 at 13:20
  • Yes saw having this error This page contains the following errors: error on line 772 at column 12: XML declaration allowed only at the start of the document Below is a rendering of the page up to the first error. – user236501 Feb 22 '13 at 13:27

1 Answers1

0

You could get you items into an array, and then sort the array, something like this...

books.xml

<?xml version="1.0"?>
<results>
   <course>1111</course>
   <books>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="248">248</isbn>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="3">3</isbn>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="224">224</isbn>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="25">25</isbn>
   </books>
</results>

test.php

$books = new DOMDocument();
$books->load( 'books.xml' );
$items = $books->getElementsByTagName("isbn");

$nodeArray = array();
foreach ($items as $item) {
    $nodeArray[$item->getAttribute('total')] = $item;
}
ksort($nodeArray);

echo "<pre>". print_r($nodeArray, true) ."</pre>";
Kevin Garman
  • 395
  • 3
  • 10