Xabi Alonso's free-kick in extra-time enabled Spain to see off the plucky challenge of South Africa and clinch third place in the Confederations Cup.
European champions Spain, whose 35-match unbeaten run came to a shock end against the United States in the semi-finals, 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.
But two goals in the final three minutes from substitute Daniel Guiza