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?

2

1 Answer 1

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,
    ]
);
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@DaltonSutton Can you expand your question explaining origin of this data data and how you gonna use this json?
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.