strange behavior of echo in php

187 views Asked by At

I am working on Commission Junction api and I want to extract link url and image url from CJ so I have made this script but the out put is not that I expected eg. you can see that echo $mat[0] is missing, so how can I solve this ? thanks

Code:

$URI = 'https://linksearch.api.cj.com/v2/link-search?'.
            'website-id=1234567'.
            '&advertiser-ids=adid'.
            '&link-type=text+link'.
            '&records-per-page=1';
$context = stream_context_create(
                array('http' => 
                            array(
                                'method' => 'GET',
                                'header' => 'Authorization: 'myapiid'
                            )
                )
            );

$data = new SimpleXMLElement(file_get_contents($URI, false, $context));
foreach ($data->links[0] as $link) 
{
    // Sanitize data.
    $pd     =   $link->{'link-code-html'};
    echo var_dump($pd);
    preg_match('#<img\s+src\s*=\s*"([^"]+)"#i',$pd,$mat);
    preg_match('#<a\s+href\s*=\s*"([^"]+)"[^>]*>([^<]+)</a>#i',$pd,$matches);
    echo '<pre>';
    print_r($matches);
    echo $matches[1];
    print_r($mat);
    echo $mat[0];
    echo '</pre>';
}

OUTPUT:
object(SimpleXMLElement)[5]
  string '<a href="http://www.dpbolvw.net/click-1234567-42452100">Save up to 70% on Airport Parking</a><img src="http://www.tqlkg.com/image-1234567-42452100" width="1" height="1" border="0"/>' (length=181)

Array
(
    [0] => Save up to 70% on Airport Parking
    [1] => http://www.dpbolvw.net/click-1234567-42452100
    [2] => Save up to 70% on Airport Parking
)
http://www.dpbolvw.net/click-1234567-42452100Array
(
    [0] =>  http://www.tqlkg.com/image-1234567-42452100
)
2

There are 2 answers

2
Borniet On BEST ANSWER

The URL you are looking for resides in

$mat[1]

not in

$mat[0]

Try a var_dump instead of a print_f. Print_f reads easier, but var_dump sometimes gives more info.

3
Muhammad Raheel On

You are missinga single quote at Authorisation

$context = stream_context_create(
                    array('http' => array(
                        'method' => 'GET',
                        'header' => 'Authorization' : 'myapiid'
                        )
                     )
);