I have this line in my code:
$item=$page->items;
$page is an array, and its content is as it should be but $item is Null. do you have any idea what could be the reason?
UPDATE:
<?php
search( "Steve Jobs" );
// Submit query to Google Web Search
function search( $query )
{
$url = "https://www.googleapis.com/customsearch/v1?key=YOUR_KEY&cx=YOUR_SEARCHE_NGINE_ID&q=" . urlencode( $query ) . "&callback=handleResponse&prettyprint=true&num=10";
$result = get_web_page( $url );
// Exception handling
if ( $result['http_code'] == 403 )
echo "... error: daily limit exceeded ...";
if ( $result['errno'] != 0 )
echo "... error: bad url, timeout, redirect loop ...";
if ( $result['http_code'] != 200 )
echo "... error: no page, no permissions, no service ...";
// Get and parse JSON output
$page = $result['content'];
$page = str_replace("// API callback\nhandleResponse(", "", $page);
$page = str_replace(");", "", $page);
$page=json_decode($page, true);
// Print results
$items=$page->items;
var_dump($items);
for ($i = 0; $i < sizeof($items); $i++)
{
$item = $items[$i];
print("<font size=\"3\">" . "" . $item->htmlTitle . "</font><br>");
print("<font size=\"2\" color=\"black\">" . $item->htmlSnippet . "</font><br>");
print("<font size=\"2\" color=\"green\">" . $item->displayLink . "</font><br>"); print("<br>");
}
}
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
?>
ANSWER:
this part should be changed since $page is an array.
$items = $page['items'];
foreach ($items as $item)
{
$item = (object) $item;
print("<font size=\"3\">" . "" . $item->htmlTitle . "</font><br>");
print("<font size=\"2\" color=\"black\">" . $item->htmlSnippet . "</font><br>");
print("<font size=\"2\" color=\"green\">" . $item->displayLink . "</font><br>"); print("<br>");
}
Simple question, simple answer:
$item is NULL because $page->items is NULL.
More details:
You're treating $page as an object, but you write it's an array.
Suggestion:
Treat $page as an array instead.
Further information:
The PHP manual has information how to treat a value like an array or like an object. Additionally if you enable warnings on your development box, you will be notified about undefined properties which are always NULL.
Update:
For your concrete code, with a slight modification this should work, just change your for loop a bit:
foreach ($items as $item)
{
$item = (object) $item;
print("<font size=\"3\">" . "" . $item->htmlTitle . "</font><br>");
print("<font size=\"2\" color=\"black\">" . $item->htmlSnippet . "</font><br>");
print("<font size=\"2\" color=\"green\">" . $item->displayLink . "</font><br>"); print("<br>");
}
$page is an array, and its content is as it should be
If $page is an array, you should access it like
$item=$page['items'];
If you provide more info you would get more helpful answer.
EDIT
First, Please make sure you have $page not empty at all.
What you have is $page=json_decode($page, true); that return an associative array and you should use the way I posted above.
If you don't want the array to be returned you should change your json_decode to return object by not passing second argument as true.
$page=json_decode($page); then you are okay with the code you have right now.
If $page is array you do this $page['items']. If it is JSON or XML you can also access ait the way you are doing. like $page->items;
Related
I am passing an array for a php page to test but I can not get the data!
$data = array(
"user_id" => $login->id,
"discount_id" => $discount,
"product_id" => $product_id->id,
"date_payment" => $test->id
);
$fields_string = http_build_query($data);
$url = "http://localhost/dev/felipe/request-checkout.php";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
$result = json_decode(curl_exec($ch));
curl_close($ch);
page.php:
extract($_POST);
$user_id = $_POST['user_id'];
$discount_id = $_POST['discount_id'];
$product_id = $_POST['product_id'];
$data_payment = $_POST['date_payment'];
echo $user_id . ' - ' . $discount_id . ' - ' . $product_id . ' - ' . $data_payment;
show null in $result in cURL. what I'm missing? how do I use the data and have a response which I did cURL?
curl_exec($ch) returns string in this format: "1 - 2 - 3 - 4".
When you try to run json_decode() on this string, it returns null because this is not correct json format.
Instead of the echo $user_id . ' - ' . $discount_id . ' - ' . $product_id . ' - ' . $data_payment;, you can endode an array/object to json string:
echo json_encode($_POST);
I am trying to upgrade a friend's Wordpress site to the latest versions of Wordpress and PHP.
All is working fine except for a scrolling news ticker he uses on his homepage that errors out with "Illegal string offset 'date'", and no news is shown.
This is the script:
<?php
$xmlOption = get_option('xmlFeed');
if (!isset($xmlOption)) {
$buildURL = "https://wordpress.org/news/feed/";
$request = curl_init();
curl_setopt($request, CURLOPT_URL, $buildURL);
curl_setopt($request, CURLOPT_HEADER, false);
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($request);
curl_close($request);
$xml = new SimpleXMLElement($result);
$channel = $xml->channel;
delete_option('xmlFeed');
$otion = array(
'xml' => $channel,
'date' => date('y-m-d')
);
add_option('xmlFeed', $option);
}
if ($xmlOption['date'] == date('y-m-d')) {
$channel = $xmlOption['xml'];
} else {
$buildURL = "https://wordpress.org/news/feed/";
$request = curl_init();
curl_setopt($request, CURLOPT_URL, $buildURL);
curl_setopt($request, CURLOPT_HEADER, false);
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($request);
curl_close($request);
$xml = new SimpleXMLElement($result);
$channel = $xml->channel;
delete_option('xmlFeed');
$otion = array(
'xml' => $channel,
'date' => date('y-m-d')
);
add_option('xmlFeed', $option);
}
$i = 0;
while ($i <= 5) {
echo "<li><a href='" . $channel->item->$i->link . "' target='_blank'>" . $channel->item->$i->title . "</a></li>";
$i++;
}
?>
I noticed the use of $otion two times, which i thought was maybe a typo. But when i changed that to $option the rest of the page was not parsed, so I guess that isn't the problem.
As I am not a coder and i pulled my hairs out for 2 nights now.
Time to get some help before i have none left.
Anyone can help me with this one?
It is not a real answer to my question, but I found another script that, with some small changes, works perfectly. So I'm happy.
<?php
$rss = new DOMDocument();
$rss->load('http://wordpress.org/news/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 5;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
echo '<li>'.$title.'</li>';
}
?>
It is smaller and cleaner.
Thanks for your help #Marcus
I want to parse some data (game names) from an external page :
https://www.mol.com/Product/GamesHive
using this code :
<?php
$url = 'https://www.mol.com/Product/GamesHive';
$content = file_get_contents($url);
$first_step = explode('<div class="col-xs-4">', $content);
$second_step = explode('</div>', $first_step[1]);
echo $second_step[0];
?>
However some data is lost. The original page has 384 items and my page only has 169 items. What's the problem?
Is this what you are trying to achieve?
<?php
$curl = curl_init();
curl_setopt_array($curl,
array(
CURLOPT_URL => 'https://www.mol.com/Product/GamesHive',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => FALSE
)
);
$response = curl_exec($curl);
curl_close($curl);
$arr = simplexml_import_dom(#DOMDocument::loadHTML($response))
->xpath('//div[#class="caption"]');
foreach ($arr as $val)
{
echo $val->h5->a . '<br />';
}
?>
I'm working on Bing Search API:
Here's the code:
<?php
if (isset($_GET['keyword'])) {
$keyword = $_GET['keyword'];
} else {
echo 'Wrong!';
}
$key = 'NNNNN'; //key for API
$root = 'https://api.datamarket.azure.com/Bing/Search/';
$search = $root . 'Web?$format=json&Query=';
$req = $search . '\'' . $keyword . '\'';
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $key . ":" . $key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($ch);
$json = json_decode($resp);
foreach ($json->d->results as $item) {
$rss_item = array(
'Title' => $item->Title,
'Description' => $item->Description,
'DisplayUrl' => $item->DisplayUrl,
'Url' => $item->Url,
);
array_push($desArray, $item->Description);
array_push($rss_array, $rss_item);
}
for ($i = 0; $i < 50; $i++) {
echo '<p class="bagi">' . '' . $rss_array[$i]['Title'] . '
' . '<img src="'.base_url().'TAMPILAN/images/open_new_tab.jpg" width="10px" height="10px" title="Open in new tab">
<br/>' .
$rss_array [$i]['Description'] . '</br>' .
'<hr/>' .
'</p>';
}
?>
I typed on my browser with:
http://localhost/MSP/SignIn/cariBing.php?keyword=statistics
But it gave me the list of the search results 50 items, complete no error, but when I used:
http://localhost/MSP/SignIn/cariBing.php?keyword=statistical+terms
It gave me Trying to get property of non-object, undefined offset, repeatedly. Then I realised the problem was on the query (keyword). The code couldn't handle such keyword that had space in it. So I tried this:
if (isset($_GET['keyword'])) {
$queryString = array();
foreach ($_GET as $keyword => $value) {
$queryString[] = $keyword .'='. $value;
}
$queryString = http_build_query($queryString, $keyword);
} else {
echo 'Wrong!';
}
I tested it with the http://localhost/MSP/SignIn/cariBing.php?keyword=statistical+terms
It gave me the results, but the results refers to a query "keyword", not "statistical terms" as I wanted, or whatever I typed.
Where did I miss? Thanks very much in advance.
I think you mean
$queryString = http_build_query(array("keyword"=>$_GET["keyword"]));
or if you want all of the $_GET parameters
$queryString = http_build_query($_GET);
replacement for your last code snippet should be
if (isset($_GET['keyword'])) {
$queryString = http_build_query($_GET);
} else {
echo 'Wrong!';
}
For reasons beyond my control I am using PHP4 to write a twitter client. Requests don't work properly - I am having a tough time seeing what's wrong. Any ideas?
I have grabbed the code and banged it in a very simple script here to illustrate essentially what's going on. I've hidden OAuth keys for security purposes.
<?php
$requestTokenURL = 'https://api.twitter.com/oauth/request_token';
$consumerKey = 'fLxA6J1111111111PnvVOg';
$consumerSecret = 'H5QxDHAOHn1111111111111Ozet1HRTtVAV1FM3oYk';
$callbackURL = 'http://www.example.com';
$signature = 'POST&' . urlencode($requestTokenURL) . '&';
$auth_params = array(
'oauth_callback' => $callbackURL,
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(time()),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
ksort($auth_params);
foreach($auth_params as $k=>$v) {
if ($k == 'oauth_callback') {
$v = urlencode($v);
}
$signature .= urlencode($k) . '%3D' . urlencode($v) . '%26';
}
$signature = substr($signature, 0, strlen($signature) - 3);
$signing_key = $consumerSecret . '&';
$oauth_signature = hmac_sha1($signing_key, $signature);
$auth_params['oauth_signature'] = $oauth_signature;
$auth_string = 'OAuth ';
foreach($auth_params as $k=>$v) {
$auth_string .= $k . '="' . urlencode($v);
$auth_string .= ($k == 'oauth_signature') ? '&' : '';
$auth_string .= '", ';
}
$auth_string = substr($auth_string, 0, strlen($auth_string) - 2);
echo 'Authorization header: <pre>';
echo $auth_string;
echo '</pre>';
echo '<br /><br />';
echo 'OAuth Signature: <pre>';
var_dump($oauth_signature);
echo '</pre>';
echo '<br /><br />';
//exit;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $requestTokenURL);
curl_setopt($curl, CURLOPT_POST, GET);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: ' . $auth_string)
);
$response = curl_exec($curl);
curl_close($curl);
var_dump($response);
/* function from PHP.net - no PHP4 built-in function */
function hmac_sha1( $key, $data ) {
$blocksize = 64;
$hashfunc = 'sha1';
if ( strlen( $key ) >$blocksize ) {
$key = pack( 'H*', $hashfunc( $key ) );
}
$key = str_pad( $key, $blocksize, chr(0x00) );
$ipad = str_repeat( chr( 0x36 ), $blocksize );
$opad = str_repeat( chr( 0x5c ), $blocksize );
$hash = pack( 'H*', $hashfunc( ( $key^$opad ).pack( 'H*',$hashfunc( ($key^$ipad).$data ) ) ) );
return base64_encode($hash);
}
?>
the thing is, I tried running this script with the values from http://dev.twitter.com/pages/auth#signing-requests and the signature and the Authorization string were exactly the same - but when I try execute with CURL with my own values (using the exacty same code) it just gives me the rather non-descript "Failed to validate oauth signature and token"
Can't believe it - just found it a second or two after posting this question. There was in fact two things wrong with it:
1) The time on my dev server wasn't properly set. After setting this correctly however, it still didn't work.
2) after setting curl_setopt($curl, CURLOPT_POST, true) everything magically worked. Hoorah!