Reputation: 19
<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
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
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
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