Berkeley CSUA MOTD:Entry 43394
Berkeley CSUA MOTD
 
WIKI | FAQ | Tech FAQ
http://csua.com/feed/
2025/07/08 [General] UID:1000 Activity:popular
7/8     

2006/6/14-18 [Computer/SW/Languages/Misc, Computer/SW/Languages/Web] UID:43394 Activity:nil
6/14    Need php assistance. Let's say I have the following XML:
          <xml><hello>&ltHello&gt</hello></xml>
        Then I parse it as follows:
          $xml_parser=xml_parser_create();
          xml_set_character_data_handler($xml_parser, "my_function");
        My problem is my handler function "my_function" will parse it as
        <, then Hello, then > separately instead of one line!  How do I make
        the XML parser parse the <hello> content just once? Thanks.
        \_ Don't forget it's &gt; and &lt; not &gt and &lt
           I'd recommend using the domxml functions:
           http://us2.php.net/manual/en/function.domxml-open-mem.php
           $x = domxml_open_mem('<xml><hello>&lt;Hello&gt;</hello></xml>');
           $d = $x->document_element();
           $hs = $x->get_elements_by_tagname('hello'); $h = $hs[0];
           $hs = $x->getElementsByTagName('hello'); $h = $hs[0]; //stupid php
           $hs = $x->get_elements_by_tag_name('hello'); $h = $hs[0];
           $h->get_content();  // == "<Hello>"
           --dbushong
           \_ How do I access deeper levels? Repeated
              $x->get_element_by_tagname('aa')->get_element_by_tagname->('bb')
              ->... doesn't seem to work
           --dbushong
              \_ note that it's get_element*s*_by_tagname.  it returns an
                 array.  note the $h = $hs[0] above.  PHP sucks and you can't
                 do $obj->method()[0]->method()[0], etc. so you have to keep
                 assigning to variables.  I actually made a function at one
                 point to make this a little easier:
                 function first($arr) { return $arr[0]; } so then you can say:
                 $h = first($x->get_elements_by_tagname('hello'));
                 If you want to access a specific deep thing, consider using the
                 xpath functions that API provides.  --dbushong
Cache (481 bytes)
us2.php.net/manual/en/function.domxml-open-mem.php
mode This optional parameter can be used to change the behavior of this function. You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. If you're using the DOM parser to parse several XML files as part of a long running script, you must free the DomDocument manually or a memory leak will occur. To free a DOM document allocated by domxml_open_mem, do the following: $doc = domxml_open_mem("$contents");