How to parse Link data from header data in PHP?

Highlighted
Shopify Partner
276 28 53

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
Give a try to Shopify APP: https://apps.shopify.com/short-track
0 Likes
Highlighted
Shopify Staff
Shopify Staff
1555 81 278

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.

1 Like
Highlighted
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
Highlighted
New Member
5 0 0

Got any reply regarding that issue.

Thanks

0 Likes
Highlighted
New Member
1 0 0

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

0 Likes