문제

I have a set of XML data like this.

<data>
    <person>
        <name>Alice</name>
        <date>343658755</date>
    </person>
    <person>
        <name>Bob</name>
        <date>655389955</date>
    </person>
    <person>
        <name>Cathy</name>
        <date>741876355</date>
    </person>
</data>

Using PHP I am parsing it with SimpleXMLElement and trying to display the timestamp in a date format.

$data = new SimpleXMLElement($xmlstr);
echo date( 'Y-m-d H:i:s', $data->person[0]->date);

This displays the following warning.

Warning:  date() expects parameter 2 to be long, object given in ....

Echoing $data->person[0]->date displays the timestamp without any problems. var_dump() shows the following output.

object(SimpleXMLElement)#3 (1) {
  [0]=>
  string(9) "343658755"
}

How do I "refer" to this string directly? If this string is inside an object why is there no Error/Warning when I echo it?

The only way I could make it work with the date() function is to convert it to the integer type like this.

echo date( 'Y-m-d H:i:s', (int) $data->person[0]->date );

Does it work with all versions of PHP? Is there anything bad about doing this?

도움이 되었습니까?

해결책

The error message is pretty clear. date() function expects the parameter to be a long, but you're passing a SimpleXML object instead.

As is evident from the var_dump() output $data->person[0]->date is an object. To get just the timestamp part, you'd have to cast it to a string.

This is applicable everywhere. When working SimpleXML, you'd have to explicitly cast the object into a string in order to access the contents inside. For this particular case, the following should work:

echo date('Y-m-d H:i:s', (string) $data->person[0]->date);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top