xml parsing issue

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

xml parsing issue

Post 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>
User avatar
seppo0010
Forum Commoner
Posts: 47
Joined: Wed Oct 24, 2007 4:13 pm
Location: Buenos Aires, Argentina

Post 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";
}

?>
Post Reply