如何使用OOP PHP将XML文本字段的不同元素分配到多个变量中?
我在MySQL数据库表中有一个文本字段,其值等于以下值:如何使用OOP PHP将XML文本字段的不同元素分配到多个变量中?,php,oop,Php,Oop,我在MySQL数据库表中有一个文本字段,其值等于以下值: $foodObject = '<?xml version="1.0" encoding="UTF-8"?> <breakfast_menu> <food> <name>Belgian Waffles</name> <prices> <price1>$5.95</price1>
$foodObject = '<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<prices>
<price1>$5.95</price1>
<price2>$8.95</price2>
</prices>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>
<A>
<A1>650</A1>
<A2>652</A2>
<A3>653</A3>
</A>
<B>
<B1>750</B1>
<B2>751</B2>
<B3>752</B3>
</B>
<C>
<C1>850</C1>
<C2>853</C2>
<C3>858</C3>
</C>
</calories>
</food>
</breakfast_menu>'
保罗·克罗维拉发布了一个精彩的链接。我走了很长的路直到。。。 安东尼奥·马克斯有一个很好的答案:
<?php
$xml_string = file_get_contents( 'in3.xml' );
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$aFoods = json_decode( $json, TRUE );
$aFoods = $aFoods[ 'food' ];
var_dump( $aFoods );
$iCountFoods = count( $aFoods );
for( $i = 0; $i < $iCountFoods; ++$i )
{
$sFoodName = $aFoods[ $i ][ 'name' ];
$sPriceOne = $aFoods[ $i ][ 'prices' ][ 'price1' ];
$sPriceOne = $aFoods[ $i ][ 'prices' ][ 'price2' ];
var_dump( $sFoodName );
var_dump( $sPriceOne );
var_dump( $sPriceOne );
}
?>
谢谢您的回答。Vladimir,我已经把问题中的数据放在一个名为foodObject
的变量中了。数据不是XML文件。我只想得到$name
,$price1
,$price2
。。。在PHP中。没问题。干得好。
<?php
$xml_string = file_get_contents( 'in3.xml' );
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$aFoods = json_decode( $json, TRUE );
$aFoods = $aFoods[ 'food' ];
var_dump( $aFoods );
$iCountFoods = count( $aFoods );
for( $i = 0; $i < $iCountFoods; ++$i )
{
$sFoodName = $aFoods[ $i ][ 'name' ];
$sPriceOne = $aFoods[ $i ][ 'prices' ][ 'price1' ];
$sPriceOne = $aFoods[ $i ][ 'prices' ][ 'price2' ];
var_dump( $sFoodName );
var_dump( $sPriceOne );
var_dump( $sPriceOne );
}
?>