Forum Moderators: coopster
<data foo="bar">
<time-layout foo="bar">
<start-valid-time period-name="Tonight">2020-01-22T18:00:00-05:00</start-valid-time>
<start-valid-time period-name="Tomorrow">2020-01-23T06:00:00-05:00</start-valid-time>
</time-layout>
</data> $xml = simplexml_load_string($contents);
$json = json_encode($xml);
$xml_array = json_decode($json, TRUE); SimpleXMLElement Object
(
[@attributes] => Array
(
[version] => 1.0
)
[data] => Array
(
[0] => SimpleXMLElement Object
(
[time-layout] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[time-coordinate] => local
[summarization] => 12hourly
)
[start-valid-time] => Array
(
[0] => 2020-01-22T18:00:00-05:00
[1] => 2020-01-23T06:00:00-05:00 But simplexml_load_string() loses the period-name value
$contents = <<<EOF
<data foo="bar">
<time-layout foo="bar">
<start-valid-time period-name="Tonight">2020-01-22T18:00:00-05:00</start-valid-time>
<start-valid-time period-name="Tomorrow">2020-01-23T06:00:00-05:00</start-valid-time>
</time-layout>
</data>
EOF;
$XML = simplexml_load_string($contents);
$result = array();
foreach ($XML->{'time-layout'}->{'start-valid-time'} as $startValidTime) {
$result[] = array (
// Cast to "string" to extract values
'period-name' => (string) $startValidTime['period-name'],
'value' => (string) $startValidTime,
);
}
print_r($result);
Array
(
[0] => Array
(
[period-name] => Tonight
[value] => 2020-01-22T18:00:00-05:00
)
[1] => Array
(
[period-name] => Tomorrow
[value] => 2020-01-23T06:00:00-05:00
)
)
$xml = simplexml_load_string($contents);
print_r($xml); [time-layout] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[time-coordinate] => local
[summarization] => 12hourly
)
[layout-key] => k-p12h-n14-1
[start-valid-time] => Array
(
[0] => 2020-01-23T20:00:00-05:00
[1] => 2020-01-24T06:00:00-05:00
[2] => 2020-01-24T18:00:00-05:00
[3] => 2020-01-25T06:00:00-05:00
[4] => 2020-01-25T18:00:00-05:00
[5] => 2020-01-26T06:00:00-05:00
[6] => 2020-01-26T18:00:00-05:00
[7] => 2020-01-27T06:00:00-05:00
[8] => 2020-01-27T18:00:00-05:00
[9] => 2020-01-28T06:00:00-05:00
[10] => 2020-01-28T18:00:00-05:00
[11] => 2020-01-29T06:00:00-05:00
[12] => 2020-01-29T18:00:00-05:00
[13] => 2020-01-30T06:00:00-05:00
)
)
when I simply do this:
$xml = simplexml_load_string($contents);
print_r($xml);
there's nothing called period-name in the results.
foreach ($XML->{'data'}->{0}->{'time-layout'}->{0}->{'start-valid-time'} as $key) {
// 2020-01-25T15:00:00-05:00 => This Afternoon
echo "$key => {$key['period-name']}\n";
$thisDate = strtotime($key);
// $forecast['period-name']['0123456789'] => 'This Afternoon'
$forecast['period-name'][$thisDate] = $key['period-name'];
}
print_r($forecast); [period-name] => Array
(
[1579982400] => SimpleXMLElement Object
(
[0] => This Afternoon
) $forecast['period-name'][$thisDate] = "{$key['period-name']}";
$thisDate = strtotime((string) $key);
$forecast['period-name'][$thisDate] = (string) $key['period-name'];