Search code examples
phpsimplexml

SimpleXML Help Needed


I am able to parse the data I want but I'm having issues trying to format the data the way I want to.

XML Data:

<home>
<data number="1" name="John" color="Red"/>
<data number="2" name="Jim" color="Blue"/>
<data number="3" name"Bob" color="Black"/>
</home>

PHP Code:

foreach ($xml->home->data as $info){
$number = $info['number'];
$name = $info['name'];
$color = $info['color'];
mysql insert into database code here
}

So from here what I want to do is combine each entry into a single variable so I can insert it into my database.

I'd like to insert this into the database like below:

1. John(Red)
2. Jim(Blue)
3. Bob(Black)

And insert it just like that as one entry/row instead of each line being inserted separately/new row for each XML Data found.(Hopefully that makes sense)


Solution

  • Requested solution

    $str = "";
    foreach ($xml->home->data as $info){
        $str .= $info['number'] . " " . $info['name']. "(".$info['color'].") ";
    }
    //insert into database using whatever method you're using. i.e. PDO.
    

    Alternative soltutions

    Alright, why don't you put it all into an array, serialize it (for future use) and then base64_encode to make it database-safe? I know you didn't specifically ask for this, but it'd definitely be a better solution.

    $insert = array();
    foreach ($xml->home->data as $info){
        $insert[$info['number']] = $info['name']."(".$info['color'].")";
        $insert = base64_encode(serialize($insert));
    }
    //insert into database using whatever method you're using. i.e. PDO.
    

    You could also use:

    $insert[] = array("id" => $info['number'], "name" => $info['name'], "colour" = > $info['color']);
    

    In this case, you can interate through the array to search easier but cannot access the specific person via their ID, if you'd like that instead, use this:

    $insert[$info['number']] = array("name" => $info['name'], "colour" = > $info['color']);
    

    This way, you can pull all the data back out of the database and decode and unseralise like this:

    seralize(base64_decode($array));
    

    And access each user by their ID via the indexes, for example (in the first case), $array[1] would contain: John(Red)

    For the second example, use $array[0] to get John(Red) and in the third example, you can use array[1] again.