1

I would like to convert an HTML ul list into a json format.

The html list is in this format:

<li><span class="orgname">Adams Center Free Library</span> <span class="status">Closed</span></li>

<li><span class="orgname">Weight Watchers Watertown</span> <span class="status">Delayed</span></li>

I'd like it to be in a json format like this:

{
  "meta": {
    "closed_count": "1",
    "delayed_count": "1"
  },
  "list": [
    {
      "data": {
        "orgname": "Adams Center Free Library",
        "status": "Closed"
      }
    },
    {
      "data": {
        "orgname": "Weight Watchers Watertown",
        "status": "Delayed"
      }
    }
  ]
}

Can someone help me out with this?

  • use this http://stackoverflow.com/questions/2817242/php-convert-ul-li-tree-html-tag-to-an-array kind of solution to get ul/li in php array the use json_encode function to get it in json formatt. – Adil Abbasi Sep 17 '14 at 09:43
  • Check here: http://stackoverflow.com/questions/23062537/how-to-convert-html-to-json-using-php – Oscar Fanelli Sep 17 '14 at 09:44

1 Answers1

0

I assume you are outputting data from some database. So add values to array and than encode to json:

$delayed = 0;
$close = 0;
$data = [];

echo "<ul>";
foreach ($myArray as $row) {
   echo "<li><span class='orgname'>{$row['orgname']}</span> <span class='status'>{$row['status']}</span></li>";
   $data[] = ['data' => ['orgmane' => $row['orgname'], 'status' => $row['status']]];
   // or if $row only has 'orgname' and 'status'
   $data[] = ['data' => $row];

   if (strtolower($row['status']) == 'delayed') {
       $delayed++;
   } else {
       $closed++;
   }
}
echo "</ul>";

json_encode(
    [
        'meta' => ['closed_count' => $closed, 'delayed_count' => $delayed],
        'list' => $data,
    ]
);
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • I love the set up of the code you provided me, however I can't use it yet. I'm actually not using a database at all. I've been forced to use a basic HTML page. – Dalton Sutton Sep 17 '14 at 10:34
  • @DaltonSutton Can you expand your question explaining origin of this data data and how you gonna use this json? – Justinas Sep 17 '14 at 10:37
  • Here is basically what I've already converted from an HTML Table into an HTML List. From the list, I wanna convert into the json feed which I can't do yet because of the foreach function. If you could help me on this, I'd appreciate it so much! snipet.co.uk/Bfh – Dalton Sutton Sep 17 '14 at 10:41
  • This is pretty much it. I believe there is an if statement in the link above that I forgot to delete but other than that, this is the main thing. I was planning on writing a function that counted the delayed and closed events later. – Dalton Sutton Sep 17 '14 at 11:00