Spain secured third place at the Confederations Cup on Sunday when Xabi Alonso curled home a long-range free kick to give them a 3-2 win over hosts South Africa after extra time.