Spain were looking defeat in the face but two goals from Daniel Guiza in the 88th and 89th minute looked to have given them a 2-1 win before South Africa equalised in injury time.
A Xabi Alonso free-kick in extra time gave a nervy Spanish side the win.