WP All Import – How to loop through XML in the function editor and access it’s values

So you’ve imported your JSON file and the plugin is returning this XML for your to map out accordingly.  GREAT!  Setting up a repeater? No problem, but you might not need all that data, maybe you need the relevant data from the array.  Here we’ll go over how to look through the data using the plugins function editor.  

Example Data:

<Addresses> 
    <item_2> 
        <AddressID>123acbdefghgi</AddressID> 
        <Address1>123 Super Fake Street</Address1> 
        <Address2/> 
        <City>Orange</City> 
        <State>CA</State> 
        <ZipCode>12345</ZipCode> 
        <Phone>(555) 555-5555</Phone> 
        <Fax>(555) 555-5555</Fax> 
        <Backline/> 
        <WheelchairAccess>Y</WheelchairAccess> 
        <AddressIsPrimary>Y</AddressIsPrimary> 
        <DoNotShowOnWeb>N</DoNotShowOnWeb> 
    </item_2> 
    <item_2>...</item_2> 
    <item_2>...</item_2> 
</Addresses> 

 

Awesome, so we have all this data, maybe your request isn’t as straightforward as just listing them all on the page in a repeater.  Let’s say, we only want to list addresses that aren’t primary and are allowed to show on the web (Well Rory, why not have this data fixed upstream, well because that isn’t always realistic and sometimes you gotta make it work).

You’ll need to pass the values from the XML like in this example:

[custom_function({item_2/DoNotShowOnWeb[1]},{item_2/AddressIsPrimary[1]},{item_2/City[1]})]

 

Not that we’ve set up what fields we need to grab, we need to actually create the function custom_function that is used above

And the code would have to be edited to something like this, and will get placed in the “function editor”

function custom_function($showonweb, $isprimary, $cities) {
    $my_cities = [];
    $showonweb = explode(",", $showonweb);
    $isprimary = explode(",", $isprimary);
    $cities = explode(",", $cities);

    for($i = 0; $i<count($showonweb); $i++){
        if (trim($showonweb[$i]) == 'N' && trim($isprimary[$i]) == 'N') {
            $my_cities[] = $cities[$i];
        }
    }
    return implode(",", $my_cities);
}

 

I hope this helps!