Xabi Alonso helped clinch third place for Spain in the Confederations Cup with his winner against South Africa.
The European champions, whose 35-match unbeaten run came to a shock end against the United States in the semi-finals, ran out 3-2 victors after extra-time.
Spain were lethargic for much of the encounter and appeared to be heading for another defeat when Katlego Mphela put Bafana Bafana ahead after 73 minutes.
saved well
However, two goals in the final three minutes from substitute Daniel Guiza turned the match around only for Mphela to send the match into extra-time with a blistering free-kick.
But Spain sealed it when Liverpool midfielder Alonso curled a 107th-minute free-kick.
Both sides had chances to win it in the first period of extra time, Joan Capdevila's cross clipping the bar while at the other end Iker Casillas saved well from Katlego Mphela - denying the striker a hat-trick when he had had burst through - and Bernard Parker. But it was Alonso who had the final say two minutes into the second period with a clever free-kick which eluded everyone and ended up in the bottom right-hand corner.