There were some problems with symfony over time. unfortunately, this is not the first time I have run into this. Has anyone ever encountered this problem? If so, thank you for your help.
Controller.php
if($xml = simplexml_load_file($feedUrl)) {
$result["chanel"] = $xml->xpath("/rss/channel/item");
foreach($result as $key => $attribute) {
$i=0;
foreach($attribute as $element) {
$ret[$i]['title'] = (string)$element->title;
$ret[$i]['category'] = (string)$element->category;
$ret[$i]['link'] = (string)$element->link;
$ret[$i]['pubDate'] = json_decode(json_encode($element->pubDate), TRUE);
$ret[$i]['enclosure'] = (array)$element->enclosure;
$ret[$i]['description'] = (string)$element->description;
$i ;
}
}
}
foreach ($ret as $feed){
$newnews = new Newsfeed();
$newnews->setTitle($feed['title']);
$newnews->setCategory($feed['category']);
$newnews->setLink($feed['link']);
$newnews->setDescription($feed['description']);
$newnews->setDate(date("Y-m-d h:i:sa", strtotime($feed['pubDate'][0])));
$newnews->setImage($feed['enclosure']['@attributes']['url']);
$newnews->setSource('2');
$entityManager->persist($newnews);
$entityManager->flush();
}
This problem
CodePudding user response:
The date()
function returns a string, so this line won't work:
$newnews->setDate(date("Y-m-d h:i:sa", strtotime($feed['pubDate'][0])));
You can probably just use:
$newnews->setDate(new \DateTimeImmutable($feed['pubDate'][0]));
CodePudding user response:
I have had this problem before. For me, when working with only Dates (no time) it was kind of misleading the fact that MySQL and thus doctrine annotations
have the Date
type, but PHP/Symfony does not.
As mentioned by Chris, the date()
function returns a string, but the class DateTime is your friend here.
Even when it is called DateTime, this class allows formatting and you can indeed, for example, retrieve only a date with it. An example would be:
$date = new DateTime('2000-01-01 12:30:25');
echo $date->format('Y-m-d');
Or in your case, in which you DO want to return the time part too:
$pubDate = new DateTime($feed['pubDate'][0])->format('Y-m-d h:i:sa');
$newnews->setDate($pubDate);
Which can be easily transformed into a one-liner.
This will show only what you ask for in the format()
function.
There is one trickiness though. In my country at least, it is very common to format dates with a slash (/
), but DateTime->format()
will not work with Y/m/d
, so keep it in mind and check for the correct format here if you are going to be using slashes.