Page 1 of 1

xml parsing issue

Posted: Mon Nov 12, 2007 10:36 am
by itsmani1
xml file

Code: Select all

<?xml version="1.0" encoding="iso-8859-1"?>
<books>
<book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
php code:

Code: Select all

$doc = new DOMDocument();
  $doc->load( 'books.xml' );
  
  $books = $doc->getElementsByTagName( "video_details" );
  foreach( $books as $book )
  {
  $publishers = $book->getElementsByTagName( "publisher" );
  $publisher = $publishers->item(0)->nodeValue;
  
  $titles = $book->getElementsByTagName( "title" );
  $title = $titles->item(0)->nodeValue;
  
  echo "$title - $author - $publisher\n";
the above code works file but there is problem if I add a tag at start and end i get problems, any help. here is my new xml.





For this xml please help me what i need to do?

Code: Select all

<?xml version="1.0" encoding="iso-8859-1"?>
<ut_response status="ok">
<books>
<book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
</ut_response>

Posted: Mon Nov 12, 2007 12:11 pm
by seppo0010
Are you sure that worked ok??
I mean... $books = $doc->getElementsByTagName( "video_details" ); should be $books = $doc->getElementsByTagName( "book" );
Correcting that It's working here...

Code: Select all

<?php
$xml = <<<xml
<?xml version="1.0" encoding="iso-8859-1"?>
<ut_response status="ok">
<books>
<book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
</ut_response> 
xml;

$doc = new DOMDocument();
$doc->loadXml($xml);

$books = $doc->getElementsByTagName( "book" );
foreach( $books as $book )
{
$publishers = $book->getElementsByTagName( "publisher" );
$publisher = $publishers->item(0)->nodeValue;

$titles = $book->getElementsByTagName( "title" );
$title = $titles->item(0)->nodeValue;

echo "$title - $author - $publisher\n";
}

?>