Parsing HTTP api response string in PHP

Viewed 343

In response of an HTTP request I get this string:

status.Action=Unknown status.ActionID=0 status.Focus.FocusPosition=0.000000 status.Focus.Status=Idle status.FocusMapValue=4096 status.Iris.IrisValue=0.000000 status.Iris.Status=Idle status.MoveStatus=Idle status.PanTiltStatus=Idle status.Postion[0]=104.350000 status.Postion[1]=3.060000 status.Postion[2]=6.656000 status.PresetID=0 status.TaskName=Unknown status.TrackStatus=Idle status.ZoomMapValue=1858 status.ZoomStatus=Idle status.ZoomValue=120

It's not a JSON, I don't think is an array, what's that?

How can I access a certain value, i.e. status.Postion[2]? Thanks.

1 Answers

This seems to do what you want. We need to separate out all the parts using explode and merge into one array. Some pieces of data appear to be part of an array themselves, such as "status.Postion[1]=3.060000", so we sniff that out with preg_match and use array_merge_recursive to make sure they get lumped together.

<?php

$response = 'status.Action=Unknown status.ActionID=0 status.Focus.FocusPosition=0.000000 status.Focus.Status=Idle status.FocusMapValue=4096 status.Iris.IrisValue=0.000000 status.Iris.Status=Idle status.MoveStatus=Idle status.PanTiltStatus=Idle status.Postion[0]=104.350000 status.Postion[1]=3.060000 status.Postion[2]=6.656000 status.PresetID=0 status.TaskName=Unknown status.TrackStatus=Idle status.ZoomMapValue=1858 status.ZoomStatus=Idle status.ZoomValue=120';

$status = array();
foreach (explode(' ', $response) as $item)
{
    $items = explode('=',$item);
    $value = $items[1];
    $props = explode('.', $items[0]);
    $data = array();
    for ($i = count($props) - 1; $i > 0; $i--)
    {
        if ($i == count($props) - 1)
        {
            if (preg_match('/([A-Za-z\.]+)\[([0-9]+)\]/', $props[$i], $matches))
            {
                $data[$matches[1]] = array((int)$matches[2] => $value);
            }
            else {
                $data[$props[$i]] = $value;
            }
        }
        else
        {
            $data[$props[$i]] = $data;
        }
    }
    $status = array_merge_recursive($status,$data);
}

echo $status['Focus']['FocusPosition'].'<br>';
echo $status['Postion'][1].'<br>';
Related