How to parse Link data from header data in PHP?

Jivan_Suhagiya
Shopify Partner
498 68 107

Hi,
Can anyone guide me how to parse next and previous page link from below code using PHP?

#...
Link: "<https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={next}, 
<https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={previous}"
#...

Thank you!

If helpful then please Like and Accept Solution.
Email: suhagiyajivan1992@gmail.com
Skype: jivan.suhagiya
First kind of Checkout Reminder APP: https://apps.shopify.com/checkout-reminder
0 Likes
Alex
Shopify Staff
Shopify Staff
1555 81 308

Try something like preg_match():

 

preg_match("/<(.*)>; rel=\"next\"/", $link_str, $matches);

$matches[1] in this case will end up being the matching substring representing the next page link. I'm not a PHP developer so there may be another way, and there's probably a better regular expression to use, but I feel that's a good stating point.

 

Cheers.

Trajche
Shopify Partner
1 0 0

Using the code below, you can call returnHeaderArray() on your 'Link' header and it will return an array that will contain previous and next links if available. 

 

function returnHeaderArray($linkHeader) {
        $cleanArray = [];

        if (strpos($linkHeader, ',') !== false) {
            //Split into two or more elements by comma
            $linkHeaderArr = explode(',', $linkHeader);
        } else {
            //Create array with one element
            $linkHeaderArr[] = $linkHeader;
        }

        foreach ($linkHeaderArr as $linkHeader) {
            $cleanArray += [
                extractRel($linkHeader) => extractLink($linkHeader)
            ];
        }
        return $cleanArray;
    }

    function extractLink($element) {
        if (preg_match('/<(.*?)>/', $element, $match) == 1) {
            return $match[1];
        }
    }

    function extractRel($element) {
        if (preg_match('/rel="(.*?)"/', $element, $match) == 1) {
            return $match[1];
        }
    }

 

0 Likes
admin18
New Member
5 0 0

Got any reply regarding that issue.

Thanks

0 Likes
pk841442
New Member
1 0 0

what is $linkheader which is passed in function please tell.......

0 Likes