<ProductCatalog>
<product>
<AtrrList>
<element Name="Storage Capacity" Value="8 GB"/>
<element Name="Interface" Value="USB 2.0"/>
</AtrrList>
</product>
</ProductCatalog>
这是我需要解析的xml,我需要使用loop将元素标记中的Name和Value放入数组中。我已设法在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>";
}
但我不能把它放在数组中,所以我可以把它保存到mysql数据库中。
我将不胜感激。
答案 0 :(得分:1)
您还可以使用SimpleXML获取值:
<?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>';
}
此代码将输出:
Storage Capacity 8 GB
---
Interface USB 2.0
---
答案 1 :(得分:0)
您可以使用DOMDocument来解析数据!
试试这个:
$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>';
}
现在结果将存储在$ rating
中答案 2 :(得分:0)
您可以使用xml_parse_into_struct()。
此函数将所有xml元素转换为多维数组。
我使用它时没有问题。
点击以下网址查看更多信息:http://php.net/manual/en/function.xml-parse-into-struct.php