Nenad Glavnik
Nenad Glavnik

Reputation: 19

Need help parsing xml

<ProductCatalog>
  <product>
    <AtrrList>
      <element Name="Storage Capacity" Value="8 GB"/>
      <element Name="Interface" Value="USB 2.0"/>
    </AtrrList>
  </product>  
</ProductCatalog>

This is xml that i need to parse, and i need Name and Value from element tag to put in array using loop.I have managed to read lines in php

foreach ($xxml->AttrList->element as $rating) {
    echo "<tr>";
    echo "<td>";
    $name = $rating['Name'];
    echo $name;
    echo "</td>";
    echo "<td>";
    $value = $rating['Value'];
    echo $value;
    echo "</td>";
    echo "</tr>";
}

but i just can't put that in array so i could save it into mysql database.

i would appreciate any help.

Upvotes: 1

Views: 70

Answers (3)

Hasse Bj&#246;rk
Hasse Bj&#246;rk

Reputation: 1601

You could use DOMDocument to parse through the data!

Try this:

$xml = <<<EOD
<ProductCatalog>
    <product>
        <AtrrList>
            <element Name="Storage Capacity" Value="8 GB"/>
            <element Name="Interface" Value="USB 2.0"/>
        </AtrrList>
    </product>  
</ProductCatalog>
EOD;

$rating = array();
$doc = new DOMDocument();
$doc->loadXML( $xml );
foreach( $doc->getElementsByTagName( 'element' ) as $node ) {
    $rating[] = array(
        'name'  => $node->getAttribute( 'Name' ),
        'value' => $node->getAttribute( 'Value' ) );

    // You can output the attributes directly
    echo '<tr><td>'
        . $node->getAttribute( 'Name' )
        . '</td><td>'
        . $node->getAttribute( 'Value' )
        . '</td></tr>';
}

Now the result will be stored in $rating

Upvotes: 0

Philipp Palmtag
Philipp Palmtag

Reputation: 1328

You can also use SimpleXML to get the values:

<?php

$xmlstr = <<<OOT
    <ProductCatalog>
    <product>
    <AtrrList>
    <element Name="Storage Capacity" Value="8 GB"/>
    <element Name="Interface" Value="USB 2.0"/>
    </AtrrList>
    </product>  
    </ProductCatalog>
OOT;

$movies = new SimpleXMLElement($xmlstr);

foreach($movies->product->AtrrList->element as $attr)
{
    echo $attr['Name'].' '.$attr['Value'];
    echo '<p>---</p>';
}

This code will output:

Storage Capacity 8 GB
---

Interface USB 2.0
---

Upvotes: 1

Rhubenni Telesco
Rhubenni Telesco

Reputation: 249

You can use the xml_parse_into_struct().

This function converts all xml elements to a multidimensional array.

i've no problems when i using it.

Check more info at: http://php.net/manual/en/function.xml-parse-into-struct.php

Upvotes: 0

Related Questions