Categories
symfony

SimpleXML in Symfony

I thought I got crazy about it. I’ve discovered SimpleXML for myself and I felt in love with it.
I never though work with XML may become such simple and then… Then I thought I really hate SimpleXML coz it took out almost hour of my life.

So here is the situation I have a XML response like:

<elements>
<element>
<value1>XXX<value1>
</element>
<element/>
<value1>YYY</value1>
<element/>
</elements>

And I’m going to parse it and find out if there is element with value1 = XXX in my database..

So generally it looks like this:

$b = new sfWebBrowser();
$b->get(XML_SOURCE_URL);
$xmlstr = $b->getResponseText();
$xml = new SimpleXMLElement($xmlstr);
foreach ($elements as $e) {
$c = new Criteria();
$c->add(TablePeer::VALUE1, $e->value1);
$dom = TablePeer::doSelect($c);
}

It looks great and I was sure it MUST work great..
And what do you think I’ve got?

PHP Fatal error: Call to undefined method SimpleXMLElement::__toString() in C:\usr\php5\PEAR\pear\symfony\vendor\creole\common\PreparedStatementCommon.php on l
ine 596

Fatal error: Call to undefined method SimpleXMLElement::__toString() in C:\usr\php5\PEAR\pear\symfony\vendor\creole\common\PreparedStatementCommon.php on line 5
96

It’s fine. I’m quickly looking through symfony forum and find out this

where someones responses to someone:

you are probably trying to insert a simplexml objet into a string column.

i.e you are doing something like :
$this->feed = new SimpleXml($feedurl);
/*..*/
$this->save();

this can not work since simplexml has no toString method and you will have to do $this->feed->asXML()

But I’m not storing anything. Moreover, when I remove criteria stuff everything works fine, I can print out values but I can’t get connected to DB.

Well, after some time of investigating I figured out that correct code is:

$b = new sfWebBrowser();
$b->get(XML_SOURCE_URL);
$xmlstr = $b->getResponseText();
$xml = new SimpleXMLElement($xmlstr);
foreach ($elements as $e) {
$c = new Criteria();
$c->add(TablePeer::VALUE1, (string)$e->value1);
$dom = TablePeer::doSelect($c);
}

See the difference? Force type conversion to string. I’m disappointed.. I’m depressed.. I need some beer because I have not expected such bullshit may happen to me.

Have a great weekend guys!