Question

I'm calling in data from a JSON file. One of my elements is:

"mainImg_select":""

Sometimes this has a value, sometimes it won't - in this case it's empty. I put this (as well as other) variables in an object called Product.

When trying to set $product -> mainImg, I'm trying to see whether the JSON value is empty or not. If it's empty, I want to get the first value of another set of images, $more_imgsand make that the main image. Here's my code:

if(!is_null($mainImg)) {
    $product->mainImage = $html->find($mainImg, 0)->src;
    for ($idx = 0; $idx < 10; $idx++) {
        $more = $html->find($more_imgs, $idx);
        if (!is_null($more)) {
            $product->moreImages[$idx] = $more->src;
        } else {
            return;
        }
    }
} else {
    for ($idx = 0; $idx < 10; $idx++) {
        $more = $html->find($more_imgs, $idx);
        if (($idx == 0) && (!is_null($more))) {
            $product->mainImage = $more->src;
        } elseif (!is_null($more)) {
            $product->moreImages[$idx] = $more->src;
        } else {
            return;
        }
    }
}

When I run the code, I get Notice: Trying to get property of non-object in relation to $product->mainImage = $html->find($mainImg, 0)->src;

I assume this has something to do with the if(!is_null($mainImg)) above it, because $mainImg SHOULD be null as defined in the JSON. If not, what's the best thing to use here?

EDIT: Here's some more detailed code for when the Product object is being set: http://pastebin.com/EEUgpwgn

Was it helpful?

Solution

You should change !is_null to !empty as is_null() will return false even if "mainImg_select" is equal to empty string "".

OTHER TIPS

Whether the $mainImg isn't found on your HTML; the code $html->find($mainImg, 0) will return null and then you will attempt to access the src parameter of a null object.

( from the Documentation of the php simple HTML Parser Library :

// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);

)

You have to do this:

if (null !== ($img = $html->find($mainImg, 0))) {
   $imgSrc = $img->src; // Here the HTML Element exists and you can access to the src parameter
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top