Search code examples
phpurlresponseresponse-headersshopify-api

Not able to retrive the URL within the link of Shopify API Response headers for pagination using limit in core php


I am not able to fetch the URL within the Link for pagination from the shopify Response headers . I will be a great help if somebody can help me to retrive the url in core php and implement pagination. Thanks in Advance


Solution

  • Here is my solution to get the next and previous links from Shopify's Link Response Header:

    Let's suppose you got the link header in:

    $link_headers = '<https://xxx.myshopify.com/admin/api/2022-10/collections/id/products.json?
    limit=50&fields=id,tags&page_info=XYXYXY>;
    rel="previous",<https://xxxx.myshopify.com/admin/api/2022-10/collections/id/products.json?
    limit=50&fields=tags&page_info=XYXYXYZ>; rel="next"';
    

    Then you can use:

    $links_arr = explode(", ", $link_headers);
        
    $cursor_links = [];
    
    for($i=0; $i < count($links_arr); $i++) {
        $tmp = explode('; rel=', $links_arr[$i]);
        $cursor_links[trim($tmp[1], '"')] = substr($tmp[0], 1, -1);
    }
    
    var_dump($cursor_links); 
    

    Which returns:

    array(2) {
    
       ["previous"]=> "https://xxx.myshopify.com/admin/api/2022-10/collections/id/products.json?
                       limit=50&fields=tags&page_info=XYXYXY",
    
       ["next"]=> "<https://xxx.myshopify.com/admin/api/2022-10/collections/id/products.json?
                   limit=50&fields=tags&page_info=XYXYXYZ"
    
    }