Hola, estoy intentando leer un archivo XML usando la libreria DOM pero algo falla, os dejo el código y el error que me da:
books.xml:
Código xml:
Ver original<?xml version="1.0"?>
<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>
Código php:
Ver original<?php
$doc = new DOMDocument();
$doc->load('books.xml');
$books = $doc->getElementsByTagName("book");
foreach($books as $book){
$authors = $book->getElementsByTagName("author");
$author = $authors->item(0)->nodeValue;
$publisher = $publishers->item(0)->nodeValue;
$title = $titles->item(0)->nodeValue;
}
echo $authors . " " . $author . " " . $publisher . " " . $title;
?>
Pero obtengo el error:
Fatal error: Call to a member function item() on a non-object in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\prueba.php on line 8
¿Me ayudáis?
Gracias.
EDITO: Lo solucioné:
Código php:
Ver original<?php
$doc = new DOMDocument();
$doc->load('books.xml');
$books = $doc->getElementsByTagName("book");
foreach($books as $book){
$authors = $book->getElementsByTagName("author");
$author = $authors->item(0)->nodeValue;
$publishers = $book->getElementsByTagName( "publisher" );
$publisher = $publishers->item(0)->nodeValue;
$titles = $book->getElementsByTagName( "title" );
$title = $titles->item(0)->nodeValue;
echo "$title - $author - $publisher\n";
}
?>