Hello and welcome to our community! Is this your first visit?
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
    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();
    $dom = new DOMDocument;
    $xpath = new DOMXpath($dom);

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

    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 . ". ";


    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. #2
    Master Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Behind the Wall
    Thanked 569 Times in 562 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


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