Home > Back-end >  get data from php simple html dom into json
get data from php simple html dom into json

Time:08-08

I'm trying to put the data I got from the php simple html dom into json but it return a invalid json.

this my code

<?php 
require 'simple_html_dom.php';
header('Content-Type: application/json; charset=utf-8');

function getUrls($url){
    $fbPost = grab_page($url);
    $postUsers = new simple_html_dom();
    $postUsers->load($fbPost);
    foreach($postUsers->find('#m_story_permalink_view h3 a') as $fbUserDiv) {
        $data = $fbUserDiv->href;
        $userurl['user_url'] = $data;
        $response["status"] = 1;
        $response["data"] = $userurl;
    
        echo json_encode($response);
    }
}
getUrls($url);

And this is the response of json i got :

{"status":1,"data":{"user_url":"\/profile.php?id=100006046927552&amp;refid=18&amp;__tn__=C-R"}}{"status":1,"data":{"user_url":"id=100006046927552"}}{"status":1,"data":{"user_url":"\/profile.php?id=100071323021139&amp;refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/ammar.hosny.33?refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/rawan.magdy.37017?refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/michaelabdo.michaelabdo.9?refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/profile.php?id=100022618071315&amp;refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/abrar.agour?refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/ahmedaymendaana?refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/ahmed.abdulrhman.9231712?refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/abdallh.gmal.393?refid=18&amp;__tn__=R"}}{"status":1,"data":{"user_url":"\/profile.php?id=100008883040689&amp;refid=18&amp;__tn__=R"}}

CodePudding user response:

You can modify your getUrls() to make valid JSON response:

function getUrls($url){
    $responses = array();
    $fbPost = grab_page($url);
    $postUsers = new simple_html_dom();
    $postUsers->load($fbPost);
    foreach($postUsers->find('#m_story_permalink_view h3 a') as $fbUserDiv) {
        $data = $fbUserDiv->href;
        $userurl['user_url'] = $data;
        $response["status"] = 1;
        $response["data"] = $userurl;
    
        $responses[] = $response;
    }
    echo json_encode($responses);
}
  • Related