You are here:  » How to print header


How to print header

Submitted by twahl on Sat, 2010-02-20 22:21 in

I am trying to print not only the records, but also header tags. For example:

<TotalPages>160</TotalPages>

Many thanks, Thomas

Submitted by support on Sat, 2010-02-20 22:38

Hi Thomas,

You just caught me! I'll answer now but it may be tomorrow before I can follow up if necessary...

What you need to do is parse your XML at a higher level to extract any "header" information you want that is higher up the tree than the repeating records that you are primarily interested in before parsing the repeated records. Because this involves parsing twice, it's more efficient to load your XML into a string rather than read the file / URL twice.

As an example, consider the following XML:

<Results>
  <Query>Bar</Query>
  <TotalPages>160</TotalPages>
  <CurrentPage>1</CurrentPage>
  <Result>
    <Foo>Bar1</Foo>
  </Result>
  <Result>
    <Foo>Bar2</Foo>
  </Result>
  <Result>
    <Foo>Bar3</Foo>
  </Result>
</Results>

To extract TotalPages before displaying each Result, you would do something like this:

<?php
  
require("MagicParser.php");
  function 
myHeaderRecordHandler($record)
  {
    global 
$TotalPages;
    
$TotalPages $record["TOTALPAGES"];
  }
  function 
myRecordHandler($record)
  {
    
// display each record here
  
}
  
$xml file_get_contents("results.xml"); // could be URL
  
MagicParser_parse("string://".$xml,"myHeaderRecordHandler","xml|RESULTS/");
  print 
"Total Pages:".$TotalPages;
  
MagicParser_parse("string://".$xml,"myRecordHandler","xml|RESULTS/RESULT/");
?>

Hope this helps!
Cheers,
David.