skip to Main Content

I Have one string which contains the link of prev and next page link:

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

expecting output

array(
    'next' => {next_page_info},
    'prev' => {prev_page_info}
);

link string has also some condition as below:

  1. string has both next and prev link

  2. string has only next link Output should be array(‘next’ => ‘{next_page_info}’ );

  3. string has only prev link Output should be array(‘prev’ => ‘{prev_page_info}’);

2

Answers


  1. You can try this function I wrote just send it the links text or the whole header info

     private function render_links($Link)
        {
            $combined_links = [];
            $links = explode(',', $Link);
            foreach ($links as $link){
                if (preg_match('#<(http(?:s)?://.*.myshopify.com/.*products.json?.*)>;.*rel=\"(.*)\"#', $link, $matches)) {
                    $combined_links[$matches[2]] = $matches[1];
                }
            }
    
            return $combined_links;
    
        }
    

    it will return the links like this as array

    "previous":"limit=1&fields=id%2Cimages&page_info=eyJkaXJlY3Rpb24iOiJwcmV2IiwibGFzdF9pZCI6NDA5OTUyMjM5NjE5NSwibGFzdF92YWx1ZSI6InNmc2Rmc2YifQ",
    "next":"limit=1&fields=id%2Cimages&page_info=eyJkaXJlY3Rpb24iOiJuZXh0IiwibGFzdF9pZCI6NDA5OTUyMjM5NjE5NSwibGFzdF92YWx1ZSI6InNmc2Rmc2YifQ"
    
    Login or Signup to reply.
  2. To return page_info for all types of URL.

    public function parsePaginationLinkHeader ($headerLink) 
    {
    
        $available_links = [];
        $links = explode(',', $headerLink);
        foreach ($links as $link){
    
            if (preg_match('/<(.*)>;srel=\"(.*)\"/', $link, $matches)) {
    
                $query_str = parse_url($matches[1], PHP_URL_QUERY);
                parse_str($query_str, $query_params);
                $available_links[$matches[2]] = $query_params['page_info'];
            }
        }
    
        return $available_links;
    }
    

    Response Dump

    array(2) {
    ["previous"]=>
    string(143) "eyJwdWJsaXNoZWRfc3RhdHVzIjoicHVibGlzaGVkIiwiZGlyZWN0aW9uIjoicHJldiIsImxhc3RfaWQiOjM3NDc0NDA1NTgxNjQsImxhc3RfdmFsdWUiOiJhbHBoYWJldCB0LXNoaXJ0In0"
    ["next"]=>
    string(188) "eyJwdWJsaXNoZWRfc3RhdHVzIjoicHVibGlzaGVkIiwiZGlyZWN0aW9uIjoibmV4dCIsImxhc3RfaWQiOjE1MjAyMzAzMzQ1NDgsImxhc3RfdmFsdWUiOiJBc3ltbWV0cmljIEhpZ2ggV2Fpc3QgU2hvcnQgU2xlZXZlIFJlZCBQYXJ0eSBEcmVzcyJ9"
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search