Reply to Re: PHP4 XML DOM

Your name:

Reply:


Posted by p.lepin on 08/17/06 12:40

mich dobelman wrote:
> Currently my web server supports only php4.
> I want to know how to parse the xml and get the
> element value using dom. I thought they have similar
> function for getting element by id or tag name, so
> far i haven't find anyting like that except fro PHP5 with
> Domdocument. Any help is appreciated.

I heartily recommend upgrading to PHP5 and DOM extension,
it's much better than PHP4's DOM XML. Nevertheless, I hope
this helps:

$xml = '<?xml version="1.0"?>
<book>
<title>hhelo</title>
</book>' ;

// here we traverse shallowly all the children nodes of a
// given node and add node values of all the text nodes
// found to the result
function get_value ( $node )
{
$result = '' ;
$sub_nodes = $node -> child_nodes ( ) ;
foreach ( $sub_nodes as $sub_node )
{
if ( $sub_node -> node_type ( ) == XML_TEXT_NODE )
{
$result .= $sub_node -> node_value ( ) ;
}
}
return ( $result ) ;
}

$doc = domxml_open_mem ( $xml ) ;

// method #1
// here we get all the <title> elements in the document,
// then get the contents of the first one of them
$titles = $doc -> get_elements_by_tagname ( 'title' ) ;
$result_1 = get_value ( $titles [ 0 ] ) ;

// method #2
// here we get the first element node child of the root
// element, then get its contents
$books = $doc -> child_nodes ( ) ;
$book_ix = $title_ix = 0 ;
while ( $books [ $book_ix ++ ] -> node_type ( ) !=
XML_ELEMENT_NODE ) ;
$titles = $books [ -- $book_ix ] -> child_nodes ( ) ;
while ( $titles [ $title_ix ++ ] -> node_type ( ) !=
XML_ELEMENT_NODE ) ;
$result_2 = get_value ( $titles [ -- $title_ix ] ) ;

// method #3
// the same thing, only using XPath
$xpath = $doc -> xpath_new_context ( ) ;
$result =
$xpath -> xpath_eval ( '//book/title/text()' ) ;
$result_3 = $result -> nodeset [ 0 ] -> content ;

--
Pavel Lepin

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация