The liver removes the yellow-brown pigment bilirubin (formed as ageing red blood cells are dismantled) from the blood and sends it, via the gall bladder and bile duct, to the intestines, where it colours the faeces brown.
I thought it was to do with dead red blood cells too. We were told this in a biology lesson. It perhaps is a simplified answer, but here must be some truth in it.