php生成xml在foreach循环中添加文本

时间:2011-05-22 21:38:43

标签: php xml string loops foreach

我想生成一个动态xml以发送到webservice。 我在xml中有一个php foreach循环。 但我无法正确理解语法。

我需要字符串看起来像这样 -

<?xml version=1.0" encoding="ISO-8859-1">
<inventoryUpdateRequest version="1.0">
<action name="bookupdate">
</action>
<SiteNameList>
<SiteName>
<vendorBookID>123456</vendorBookID>
</SiteName>
<SiteName>
<vendorBookID>788901</vendorBookID>
</SiteName>
</SiteNameList>
</inventoryUpdateRequest>

The <SiteName>...</SiteName> is looped for each value found.

到目前为止我的代码就是这个 -

<?php 
$xml =
'<?xml version="1.0" encoding="ISO-8859-1">
<inventoryUpdateRequest version="1.0">
<action name="bookupdate">
</action>
<SiteNameList>
'.
$ids_orderlineitem_portal_rownum = 1;
foreach($ids_row['order_line_item::bookID'] as  $ids_orderlineitem_portal_row=>$ids_orderlineitem_portal)
{
.'
<SiteName>
<vendorBookID>
'.$ids_row['order_line_item::bookID'][$ids_orderlineitem_portal_row].'
</vendorBookID>
</SiteName>
'.if($ids_orderlineitem_portal_rownum == 0) break; else  $ids_orderlineitem_portal_rownum++;
}//portal_end
.'
</SiteNameList>
</inventoryUpdateRequest>'
;
$url ='https://inventoryupdate.sitename.com';
$port = 80;

$response = xml_post($xml, $url, $port);    
?>

帮助?如何让循环输出我需要的格式?

1 个答案:

答案 0 :(得分:1)

很难知道这是否有效,因为我不知道输入数据的格式是什么,但希望这应该有效,或者至少更接近你需要的内容:

<?php 
    $xml =
    '<?xml version="1.0" encoding="ISO-8859-1">
    <inventoryUpdateRequest version="1.0">
    <action name="bookupdate">
    </action>
    <SiteNameList>';
    foreach($ids_row['order_line_item::bookID'] as  $book_id)
    {
        $xml .= '
        <SiteName>
        <vendorBookID>
        '.$book_id.'
        </vendorBookID>
        </SiteName>';
    }//portal_end
    $xml .= '
    </SiteNameList>
    </inventoryUpdateRequest>'
    ;

    $url ='https://inventoryupdate.sitename.com';
    $port = 80;

    $response = xml_post($xml, $url, $port);    
?>