php-general | 2004032

[PHP] Re: extracting data from XML file to PHP variable .. From: Jason Barnett (jasbarne <email protected>)
Date: 03/31/04

Kenn Murrah wrote:

> Greetings.
>
> I've been RTFM all morning and for the live of me can't figure out how
> to relate the element name to its data, e.g. if the element name is
> "fullname" and the data is "John Doe' how do I achieve $fullname =
> "John Doe" .... I must not be understanding how xml_parse works, and
> my searches have turned up nothing.

Perhaps you should consider how you want your data structured. I'm not
sure what you're doing exactly, but consider the following file:
<root>
   <people>
     <person>
       <fullname>John Doe</fullname>
     </person>
   </people>
   <person>
     <fullname>Ken Murrah</fullname>
   </person>
   <person>
     <fullname>Jason Barnett</fullname>
   </person>
</root>

Do you see the problem? By assigning the character data to the element
tag each time, you would end up with $fullname = "Jason Barnett". Would
you want this to be an array instead to grab all "fullname" tags?

>
> Any help would be appreciated.
>
> thanks.
>
>
>
>
> function startElement($xml_parser, $name, $attributes) {
>
> print("<p><i>Encountered Start Element For: </i>$name\n");
> }
> function endElement($xml_parser, $name) {
> print("<p><i>Encountered End Element For: <i/>$name\n");
> }
> function characterData($xml_parser, $data) {
> if ($data != "\n") {
> $data = ereg_replace ("\:", "&", $data);
> print ("<p><i>Encountered Character Data: </i>$data\n");
> }
> }
> function load_data($file) {
> $fh = fopen($file, "r") or die ("<p>COULD NOT OPEN FILE!");
> $data = fread($fh, filesize($file));
> return $data;
> }
> $xml_parser = xml_parser_create();
> xml_set_element_handler ($xml_parser, "startElement", "endElement");
> xml_set_character_data_handler($xml_parser, "characterData");
> xml_parse($xml_parser, load_data($file)) or die ("<p>ERROR PARSING XML!");
> xml_parser_free($xml_parser) ;
>
>

If you're trying to keep track of attributes more directly you might try
using the Dom functions instead.
PHP4: http://www.php.net/domxml
(recommended) PHP5: https://www.zend.com/php5/articles/php5-xmlphp.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php