4

I have some PHP code to turn an XML file into a CSV file. During testing, I am not creating a CSV file, just echoing the results in a CSV format.

Whenever XMLReader reaches an empty element, it outputs all the attributes of the element.

1) Is there a way to output the attribute name with it's values i.e. (is there an $xml->AttributeName that goes with the $xml->value)?

2) Is there a way to sort for all attributes in the entire tree and not just those in the empty element?

<?php 

ini_set('memory_limit','50M');

$x = file_get_contents('H8_data.xml');

$xml = new XMLReader(); 
$xml->open('H8_data.xml', null, 1<<19); 

$num = 1;
while ($xml->read() && $num <= 2000) {
    if($xml->isEmptyElement) {
        if($xml->hasAttributes)  {
            while($xml->moveToNextAttribute()) { 
                echo $xml->value, ', '; 
            }
        }
    echo '<br />';
    $num++;
    }
}

?>

3
  • Syntax error: echo $xml->value, ', '; should be echo $xml->value . ', '; ?? Commented Jan 25, 2010 at 2:44
  • actually both are acceptable. I would have to use the latter if I was creating a variable, but echo supports commas. Commented Jan 25, 2010 at 2:46
  • This is not a syntax error, echo accepts any number of arguments separated by commas. Commented Jan 25, 2010 at 2:48

2 Answers 2

5

$xml->name returns the qualified name of the node. Because attributes are nodes with XMLReader::ATTRIBUTE type, $xml->name will return the name of current attribute in that case. Below is version of code, which outputs both attribute names and values.

<?php 

ini_set('memory_limit','50M');

$x = file_get_contents('H8_data.xml');

$xml = new XMLReader(); 
$xml->open('H8_data.xml', null, 1<<19); 

$num = 1;
while ($xml->read() && $num <= 2000) {
    if($xml->isEmptyElement) {
        if($xml->hasAttributes)  {
            while($xml->moveToNextAttribute()) { 
                echo $xml->name, ' = ', $xml->value, ', '; 
            }
        }
    echo '<br />';
    $num++;
    }
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1

$xml->name ?

http://www.php.net/manual/en/class.xmlreader.php#xmlreader.props.name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.