Results 1 to 1 of 1

Thread: XML Parsing using PHP {Intermediate}

  1. #1

    XML Parsing using PHP {Intermediate}

    This will probably be an easy fix for someone who is familiar with XML. I have gone through the tutorial from this site (XML Parsing using PHP intermediate). Everything is working except for one problem. Every time I refresh my script in my browser, I get a different amount of results. Most times the script only parses 4 results form the xml file but sometimes it parses all 11 results like it should.


    Here is what my code looks like:


    #################################
    ?php

    $xml_file = "http://api.votesmart.org/Candidates.getByOfficeState?key=72b64124ada95f14e3 581b010e133d9b&officeId=5&stateId=UT&electionYear= 2008";


    $xml_id_key = "*CANDIDATELIST*CANDIDATE*CANDIDATEID";
    $xml_ln_key = "*CANDIDATELIST*CANDIDATE*LASTNAME";

    $story_array = array();

    $counter = 0;
    class xml_story{
    var $vs_id, $vs_ln;
    }

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

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

    function contents($parser, $data){
    global $current_tag, $xml_id_key, $xml_ln_key, $counter, $story_array;
    switch($current_tag){
    case $xml_id_key:
    //$story_array[$counter] = new xml_story();
    $story_array[$counter]->vs_id = $data;
    break;
    case $xml_ln_key:
    $story_array[$counter]->vs_ln = $data;
    $counter++;
    break;

    }
    }

    $xml_parser = xml_parser_create();

    xml_set_element_handler($xml_parser, "startTag", "endTag");

    xml_set_character_data_handler($xml_parser, "contents");

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

    $size = filesize($xml_file);
    $data = fread($fp, 8000) or die("Could not read file");

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

    xml_parser_free($xml_parser);

    fclose($fp);

    ?>


    <html>
    <head>
    <title>CNT HEADLINE NEWS</title>
    </head>
    <body bgcolor="#FFFFFF">
    <?php
    for($x=0;$x<count($story_array);$x++){
    echo "\t<h2>" . $story_array[$x]->vs_id . "</h2>\n";
    echo $story_array[$x]->vs_ln . "\n";
    }

    echo "<br><br>";

    print_r($story_array);
    echo "<br><br>";
    var_dump($story_array);
    ?>

    </body>
    </html>


    ################################
    Last edited by whee1206; July 25th, 2009 at 11:12 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Home About kirupa.com Meet the Moderators Advertise

 Link to Us

 Credits

Copyright 1999 - 2012