使用具有多个属性的PHP将新数据行添加到XML

时间:2012-10-25 17:25:10

标签: php xml wordpress simplexml

我希望在保存自定义帖子类型后使用WordPress向XML文件添加新行。我对如何添加新行但每行有多个属性感到困惑。我的XML文件的每一行如下

<markers>
    <marker name="" lat="" lng="" type="" address="" phone="" hours1="" />
    <marker name="" lat="" lng="" type="" address="" phone="" hours1="" />
    <marker name="" lat="" lng="" type="" address="" phone="" hours1="" />
</markers>

对于我保存的每个新商店,我希望它将所有数据添加到一个新行。我不知道是否需要创建一个新的子项然后添加它,因为我之前从未真正将数据添加到XML文件中,令人费解。我当前文件的代码如下

$xml = new SimpleXMLElement('<xml/>');
$stores = get_posts( array( 'post_type'=>'store', 'numberposts'=>-1 ) );
$xml->addChild('markers');

$name = $_POST['post_name'];
$lat = $_POST['wpcf']['latitude'];
$lng = $_POST['wpcf']['longitude'];
$type = $_POST['wpcf']['features'];
$address = $_POST['wpcf']['address'];
$phone = $_POST['wpcf']['telephone'];
$hours1 = $_POST['wpcf']['mon-fri'] . ", " . $_POST['wpcf']['saturday'] . ", " . $_POST['wpcf']['sunday'] ;

 $xml->stores->addChild('marker');
 $xml->stores->addChild('name', $name);
 $xml->stores->addChild('lat', $lat);
 $xml->stores->addChild('lng', $lng);
 $xml->stores->addChild('type', $type);
 $xml->stores->addChild('address', $address);
 $xml->stores->addChild('phone', $phone);
 $xml->stores->addChild('hours1', $hours1);

$file = SITE_URL() . '/testing.xml';
$open = fopen($file, 'w') or die ("File cannot be opened.");
fwrite($open, $xml->asXML());
fclose($open);

1 个答案:

答案 0 :(得分:0)

实现您正在寻找的XML输出的正确语法是(省略了一些属性):

$xml = new SimpleXMLElement('<xml/>');
$xml->addChild("markers");
$xml->markers->addChild("marker");
$xml->markers->marker->addAttribute('lat', 0);
print_r($xml->saveDoc());

将输出:

<?xml version="1.0"?>
<xml><markers><marker lat="0"/></markers></xml>