Dynamic width of div element?

I’m not very experienced with CSS, and I apologize if this is a dumb question. Basically, I have a few photographs being dynamically loaded onto an html/php page, and I want to have a border around each of the individual pictures. The tricky part is that the photos are of varying sizes. I can pull the widths and heights from an xml document using php, but my question is how to size the borders accordingly. Here is the php code that I currently have:

require("getphotographyxml.php"); //extracts data from xml doc
for($i = 0; $i < count($story_array); $i++){
     echo "<div class='photo'>";
     echo "Width: " . $story_array[$i]->width . "px, Height: " . $story_array[$i]->height . "px;"; //correctly displays width and height of each photo
     echo "<img src='" . $story_array[$i]->url . "'></div>";
     echo "<div class='phototitle'>" . $story_array[$i]->title . "</div>";

And this is the relevant part of my style.css file:

.photo {
    border-style: groove;
    border-width: thin;
    border-color: #CCCCCC;

I posted in the HTML/CSS forum because it seems to me that the issue is fundamentally dealing with CSS, as I think I’ve done most of the php work correctly. If someone could point me in the right direction, I’d be greatly appreciative.