We consider an embedded modular curve in a locally symmetric space M attached to an orthogonal group of signature (p, 2) and associate to it a nonholomorphic elliptic modular form by integrating a certain theta function over the modular curve. We compute the Fourier expansion and identify the generating series of the (suitably defined) intersection numbers of the Heegner divisors in M with the modular curve as the holomorphic part of the modular form. This recovers and generalizes parts of work of Hirzebruch and Zagier.