Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jan 2014
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Simple JSONReader code not working

    I am trying to use JSONReader (along with PHP & XPATH) to parse a very large JSON file, then display search results. A stream parser (such as JSONREader) is recommended over JSON_decode when parsing large files. This simple code below is not displaying any results (in the echo statements). Any advice is greatly appreciated.

    $reader = new JSONReader();
    $reader->open('products.json');
    $dom = new DOMDocument;
    $xpath = new DOMXpath($dom);

    while ($reader->read() && $reader->name !== 'product') {
    continue;
    }

    while ($reader->name === 'product') {
    $node = $dom->importNode($reader->expand(), TRUE);

    $name = $xpath->evaluate('string(name)', $node);
    $price = $xpath->evaluate('string(price)', $node);
    echo "Name: " . $name . ". ";
    echo "Price: " . $price . ". ";

    $reader->next('product');
    }


    Here is a snippet of the JSON file:
    {
    "products": {
    "product" : [
    { "name" : "Dell 409", "price" : 499.99},
    { "name" : "HP Lap top", "price" : 599.99},
    { "name" : "Compaq 11", "price" : 299.99}


    ] }}

  • #2
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,342
    Thanks
    13
    Thanked 349 Times in 345 Posts
    I would suspect that your 2nd while() loop doesn’t get any results because the 1st while() loop already finished the json file (similar to an SQL select query). since I didn’t find the docs for JSONReader I can’t tell you what the correct procedure is but I would stab a guess at something like
    PHP Code:
    while ($reader->read()) {
      if (
    $reader->name === "product")
        
    // ...

    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer


  •  

    LinkBacks (?)

    1. 05-15-2014, 12:34 AM

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •