When you select the Source tab in an RTF field, the Tridion GUI applies an XSLT against the XHTML that exists; this causes the escaping of the HTML you seem to desire.
The same action is undertaken when you select Save in the GUI.
The XSLT is located in the Schema as a property of the RTF field - you will see a button titled
Edit Formatting Features and the XSLT is prompted when you click this and then select the
Filtering XSLT tab.
You simply need to apply the same XSLT (which you'd probably need to hand manage between where your original input is and the Tridion Schema - although in my experience this will VERY rarely be updated).
Where and how you apply that will depend on where you are needing to do the transformation (there's a very high degree of guesswork here as your question is far from clear and would benefit from a lot more context of the actual requirement)