0

I would like to iterate over an array and from that array create a string. However, each string needs to be of certain size (500 bytes).

So my array looks like:

Array
(
    [0] => Array
        (
            [name] => shirt
            [price] => 1.25
        )

    [1] => Array
        (
            [name] => car
            [price] => 25.10
        )
    ...
)

$str = "";

foreach($arr as $v) {
    $str .= "<name>".$v['name']."</name>";
    $str .= "<price>".$v['price']."</price>";
}

Output should be something like:

str1 = '<name>shirt</name><price>1.25</price><name>car</name><price>25.10</price>...' // until 500 bytes or less. 
str2 = '<name>shirt</name><price>1.25</price><name>car</name><price>25.10</price>...' // until 500 bytes or less. 

// I need complete tags. So I can't have a string that looks like:

str = '<name>flower</name><pri';
4

2 回答 2

1

将每个段保存为少于 500 个字符。

$xml = array();
$str = '';
foreach($arr as $v)
{
    $temp = "<name>".$v['name']."</name>";
    $temp .= "<price>".$v['price']."</price>";

    if(mb_strlen($str . $temp) > 500)
    {
        $xml[] = $str;
        $str = '';
    }
    $str = $temp;
}
$xml[] = $str;

print_r($xml);
于 2012-02-28T21:52:47.983 回答
1

str_split听起来是个不错的选择。

于 2012-02-28T21:26:06.510 回答