On the Republican side, businessman Dee Adcock easily defeated Beverly Plosa-Bowser, a retired Air Force colonel, for the nomination.
The real race was among Democrats, who have a strong registration edge in a district split evenly between Philadelphia and Montgomery County. The seat had been held by Rep. Allyson Y. Schwartz, who lost her bid for the nomination for governor Tuesday.
Once viewed as a slam-dunk for Margolies, the contest had grown tight in the final weeks as she, Boyle, State Sen. Daylin Leach, and physician Val Arkoosh blanketed the airwaves with ads and attacked one another in mailers.
Boyle was last in fund-raising but benefited from strong union support and overcame opponents' attempts to paint him as soft on abortion rights. The only candidate who lives in Philadelphia, he won nearly three-quarters of the votes there. In Montgomery County, Margolies led Boyle, 2-1.
Boyle's brother, State Rep. Kevin Boyle, acknowledged that divide Tuesday, saying the campaign succeeded by building a strong base of support in Northeast Philadelphia and spreading "it out to Montgomery County."
After calling to congratulate Boyle, Margolies thanked staff and supporters who gathered at State Rep. Madeleine Dean's home in Jenkintown.
"I just want to let all of you know how important it is to make sure that women are represented," she said. "I think it's terribly important to continue this, to make sure that women run."
Schwartz had been the only woman in Pennsylvania's congressional delegation.
Margolies held the seat from 1993 to 1995, but was ousted after voting in favor of President Bill Clinton's tax increase. The Clintons - now her son's in-laws - are now among her strongest supporters.
Margolies' campaign was dogged over the last six months by weak fund-raising and allegations of misused campaign funds.
Since her last stint in Congress, Margolies, 71, of Plymouth Township, has been running the Philadelphia-based nonprofit Women's Campaign International.
Leach, 52, of Wayne, has been in the state Senate since 2009. Before that he was a state representative and a lawyer.
Arkoosh, 53, of Glenside, is an obstetric anesthesiologist who raked in significant contributions from medical and university groups. She raised the most of any candidate - nearly $2 million by the end of April.
Earlier in the day, all four candidates traveled the district, shaking hands and seeking out undecided voters.
"It seems to be going great, but it's hard to know exactly," said Leach, handing out campaign fliers at Pollock School in the Torresdale section of Philadelphia.
Margolies made dozens of stops across the district, one of which became largely a family affair. At the Philadelphia Protestant Home on Tabor Avenue, Margolies ran into several of her children and grandchildren.
"It's become kind of an impromptu reunion," said Marc Mezvinsky, her son, who is married to Chelsea Clinton. "It's rare that we're all in the same city at the same time."