get attribute value from an XML tag

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Alex

    get attribute value from an XML tag

    hello,

    how do i get the attribute "href" value using the following script ?

    <news>
    <story>
    <headline href=http://www.bibo.com Godzilla Attacks LA! </headline>
    <description>Eq .........

    ---------------------------------------

    <?php

    $xml_file = "news.xml";

    $xml_headline_k ey = "*NEWS*STORY*HE ADLINE";
    $xml_descriptio n_key = "*NEWS*STORY*DE SCRIPTION";

    $story_array = array();

    $counter = 0;
    class xml_story{
    var $headline, $description;
    }

    function startTag($parse r, $data){
    global $current_tag;
    $current_tag .= "*$data";
    }

    function endTag($parser, $data){
    global $current_tag;
    $tag_key = strrpos($curren t_tag, '*');
    $current_tag = substr($current _tag, 0, $tag_key);
    }

    function contents($parse r, $data){
    global $current_tag, $xml_headline_k ey, $xml_descriptio n_key, $counter,
    $story_array;
    switch($current _tag){
    case $xml_headline_k ey:
    $story_array[$counter] = new xml_story();
    $story_array[$counter]->headline = $data;
    break;
    case $xml_descriptio n_key:
    $story_array[$counter]->description = $data;
    $counter++;
    break;
    }
    }

    $xml_parser = xml_parser_crea te();

    xml_set_element _handler($xml_p arser, "startTag", "endTag");

    xml_set_charact er_data_handler ($xml_parser, "contents") ;

    $fp = fopen($xml_file , "r") or die("Could not open file");

    $data = fread($fp, filesize($xml_f ile)) or die("Could not read file");

    if(!(xml_parse( $xml_parser, $data, feof($fp)))){
    die("Error on line " . xml_get_current _line_number($x ml_parser));
    }

    xml_parser_free ($xml_parser);

    fclose($fp);

    ?>

    <html>
    <head>
    <title>CNT HEADLINE NEWS</title>
    </head>
    <body bgcolor="#FFFFF F">
    <?php
    for($x=0;$x<cou nt($story_array );$x++){
    echo "\t<h2>" . $story_array[$x]->headline . "</h2>\n";
    echo "\t\t\n";
    echo "\t<i>" . $story_array[$x]->description . "</i>\n";
    }
    ?>

    </body>
    </html>

    ---------------------------------------------------------------



    many thanks!

    Alex




  • Janwillem Borleffs

    #2
    Re: get attribute value from an XML tag

    Alex wrote:
    how do i get the attribute "href" value using the following script ?
    >
    [...]
    function startTag($parse r, $data){
    global $current_tag;
    $current_tag .= "*$data";
    }
    >
    By adding support for a third argument to this functions, which will either
    be null or an array containing the attribute names and their values (when
    available).

    See: http://www.php.net/xml_set_element_handler


    JW


    Comment

    Working...