Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created January 13, 2015 21:05
Show Gist options
  • Save wesleybliss/e8a072a85cd678eafce0 to your computer and use it in GitHub Desktop.
Save wesleybliss/e8a072a85cd678eafce0 to your computer and use it in GitHub Desktop.
Recursing all nodes in an XML document (example)
<?php
/**********************************
* CONFIG
*********************************/
// Config (change these if you want)
define( 'DISABLE_TIME_LIMIT', true );
define( 'DISABLE_OUTPUT_BUFFERING', true );
define( 'CUSTOM_ERROR_HANDLING', false );
// Don't allow PHP to stop after global timeout setting
if ( DISABLE_TIME_LIMIT ) set_time_limit( 0 );
if ( DISABLE_OUTPUT_BUFFERING ) {
// Remove output buffering
while ( ob_get_level() ) ob_end_clean();
// Output buffers directly
ob_implicit_flush( true );
}
if ( CUSTOM_ERROR_HANDLING ) {
// Custom error handling
error_reporting( 0 );
function handleError( $errno, $errmsg, $filename, $linenum, $vars ) {
exit(
'[' . $errno . '] Line #' . $linenum .
PHP_EOL . $errmsg . PHP_EOL . ' in ' . $filename
);
}
$old_error_handler = set_error_handler( 'handleError' );
}
function showUsage() {
print '@todo Show usage';
}
// Only allow this script to be run via the command line
if ( strtoupper(PHP_SAPI) !== 'CLI' ) {
print 'This script can only be run via the command line.';
showUsage();
exit( 1 );
}
/**********************************
* USER FUNCTIONS
*********************************/
/**
* Recursively traverses an XML tree, printing each node's value.
*
* @param [XMLNodeList] $xml The node list to traverse.
* @param [Integer] $indent The number of indents (just for visuals)
* @return [Void]
*/
function recurseEntities( $xml, $indent ) {
foreach ( $xml->children() as $child ) {
foreach ( $child->attributes() as $attr => $attrVal ) {
print PHP_EOL .str_repeat('-', $indent) .
' ' . $attr . ' = ' . $attrVal;
//if ( $attrVal == "yes" ) {
recurseEntities( $child->children(), ($indent + 1) );
//}
}
}
}
// Make sure we have a file argument
if ( empty( $argv[1] ) ) {
print 'Error [01]: You must specify a file to traverse.';
showUsage();
exit( 1 );
}
$xmlFilePath = $argv[1];
if ( !file_exists($xmlFilePath) ) {
print 'Error: [02]: Specified XML file does not exist or can\'t be accessed.';
exit( 2 );
}
$xmlref = simplexml_load_file( $xmlFilePath );
recurseEntities( $xmlref, 0 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment