开发者

parsing xml with php, children

开发者 https://www.devze.com 2023-01-02 07:24 出处:网络
H开发者_如何学Pythonello I successfully created my parser Everything is working great except one thing since my xml is formated a little different and I am totally lost on how to assign variable to th

H开发者_如何学Pythonello I successfully created my parser Everything is working great except one thing since my xml is formated a little different and I am totally lost on how to assign variable to the children of <photos>.


I think parsing the XML data into a tree like structure would be helpful. I did this for you, look here:

<?php
$data = '
<item>
  <url /> 
  <name /> 
  <photos>
    <photo>1020944_0.jpg</photo> 
    <photo>1020944_1.jpg</photo> 
    <photo>1020944_2.jpg</photo> 
  </photos>
  <user_id /> 
</item>';

$tree = array();
$stack = array( &$tree );

function startElement( $parser, $name, $attrs ) {
  global $stack;
  $t = &$stack[ count( $stack ) - 1 ];
  $t[ $name ][] = array();
  $n = count( $t[ $name ] );
  array_push( $stack, &$t[ $name ][ $n - 1 ]);
}

function endElement( $parser, $name ) {
  global $stack;
  array_pop( $stack );
}

function characterData( $parser, $data ) {
  global $stack;
  $t = &$stack[ count( $stack ) - 1 ];
  $t[ '#CDATA' ] = trim( $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, $data, TRUE );

foreach( $tree[ 'ITEM' ][ 0 ][ 'PHOTOS' ][ 0 ][ 'PHOTO' ] as $photo ) {
  echo "{$photo[ '#CDATA' ]}\n";
}
?>

In fact, I have (amateurish) reimplemented what SimpleXML already gives you:

<?php
$xml = new SimpleXMLElement( $data );
foreach( $xml->photos->photo as $photo ) {
  echo "$photo\n";
}
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消