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
  • Why not tell us why are doing this and let us show you the correct way? Commented Feb 28, 2012 at 21:28
  • basically, I need strings that contain both tags, <name> and <price>. So I would like to push as many array elements into a string. But since I know the array has a lot of elements, and I also know that each strings has to be shorter than 500 bytes, then is likely I'll need several strings. Commented Feb 28, 2012 at 21:44
  • You either need 500-character long strings, or you need strings that abide by tag boundaries. You cannot have both. Commented Feb 28, 2012 at 21:51
  • can you please elaborate a bit more about that? Commented Feb 28, 2012 at 22:01

2 Answers 2

1

Save each segment to as less than 500 characters.

$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);
Sign up to request clarification or add additional context in comments.

Comments

1

str_split sounds like a good candidate.

3 Comments

Good default, but that looks like XML above which will be invalid if it's split like this.
You are right. I was thinking Kayla wanted to stream the output in small chunks.
the issue with str_split, is that it will break the string at the wrong place. all strings should contain both tags: name, price

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.