recently I started using MongoDB and I found this https://packagist.org/packages/mongodb/mongodb package. it seems a good one to work with. but I cant get an array when I want to find a specific data or the whole collection. it gives me object or collection of objects( depends on the find() or findMany() method) but i need a PHP array to work with it( do some loops, check some conditions or pass them into View side).
use MongoDB\Client;
$mongoObject = new Client();
$usersCollection = $mongoObject->selectDatabase('test')->selectCollection('users');
$users = $usersCollection->find([]);
foreach ($users as $user) {
echo "<pre style='font-size: 20px;'>";
var_dump($user);
echo "</pre>";
}
die();
the package is recommanded by php.net himself check it out here: http://php.net/manual/en/mongodb.tutorial.library.php
Is there anybody that can help me?
thanx to http://php.net/manual/en/mongodb.tutorial.library.php this page, I can simply use below structure to get the data.
use MongoDB\Client;
$mongoObject = new Client();
$usersCollection = $mongoObject->selectDatabase('test')->selectCollection('users');
$users = $usersCollection->find([]);
foreach ($users as $user) {
echo $user['_id'], ': ', $user['company_name'], "<br>";
}
die();
Related
I have successfully fetched data from twitter API in the form of JSON. But the time provided by twitter is still not in the dateformat I need, so I think I have to edit it first. The problem is I don't know how to edit a JSON file with PHP.
Now if I want to edit the 'created_at', how do I do it? So far, here's what I got.
$results = search($query);
header('Content-Type: application/json');
$results= json_encode($results, JSON_PRETTY_PRINT);
echo $results;
file_put_contents('json_result.json', $results);
$contents = file_get_contents('json_result.json');
$contentsDecoded = json_decode($contents, true);
echo $contentsDecoded['statuses']->created_at;
foreach ($contentsDecoded['statuses'] as $tweet) {
$date = new DateTime($tweet->created_at);
$formatted_date = $date->format("d-m-Y");
echo "Date ".$formatted_date;
}
I still get error saying that it's a property of non-object...
Edit it before putting it in the file instead of putting it, getting it again, saving again.
I think the problem lies in one of these lines:
echo $contentsDecoded['statuses']->created_at;
foreach ($contentsDecoded['statuses'] as $tweet) {
Either $contentsDecoded['statuses'] has property created_at or is an array
So accessing property created_at of an array is not valid. Try to remove that line
I'm trying to display stored data form the mongodb using the php? But it display's all the header file including data. How to ignore the header information?
It shows like
{ "_id" : ObjectId("550ee694c5c9f2729b066c23"),
I want result as
550ee694c5c9f2729b066c23
my php code:
$db = new Mongo();
$query = $db->selectDB('test');
$collections = new MongoCollection($query,'demo');
$coursor = $collections->find();
foreach ($coursor as $doc)
{print_r($doc);}
You can find the value of the ObjectId() object as a lowercase hexadecimal string using valueOf() method.
ObjectId("550ee694c5c9f2729b066c23").valueOf() = 550ee694c5c9f2729b066c23
For more details you can check documentation :
http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/
Actually { print_r($doc); } shows header too. There should be some kind of a Key to know which data we need. So we cannot remove them.
$db = new Mongo();
$query = $db->selectDB('test');
$collections = new MongoCollection($query,'demo');
$coursor = $collections->find();
foreach ($coursor as $doc)
{
echo $doc['id'];
}
Will give you only 550ee694c5c9f2729b066c23
I am attempting to only run a loop if xml results actually exist. I am getting the xml results via:
$albums = simplexml_load_string(curl_get($api_url . '/videos.xml'));
What I want to be able to do is that on the next line say:
if($albums = hasAValue())
// Loop
Any ideas? Or a way to check before I load the XML data?
Side note: This is using the Vimeo API.
No, you need to further go down with the resultant with the namespace, reach till body give the xpath and work on.
$albums->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
To be specific, let me know the XML response you are getting i will let you the output.
UPDATED
$albums = simplexml_load_string("#your response#");
echo count($xml->children());
The dirty way:
$albums = #simplexml_load_string(curl_get($api_url . '/videos.xml'));
if ($albums)
{
...
}
This is dirty because of the Error Control Operator # which is used to "deal" with the error cases (e.g. problem fetching the remote location).
The alternative is to differentiate more here:
$xml = curl_get($api_url . '/videos.xml');
$albums = NULL;
if ($xml)
{
$albums = simplexml_load_string($xml);
}
if ($albums)
{
...
}
I tried this and even added a cursor but it would still retrieve only the first 100 followers.
<?php
$cursor = -1;
$account_from = 'username';
do
{
$json = file_get_contents('http://api.twitter.com/1/statuses/followers/' . $account_from .'.json?cursor=' . $cursor);
$accounts = json_decode($json);
foreach ($accounts->users as $account)
{
$a[] = $account->screen_name ;
}
$cursor = $accounts->next_cursor;
}
while ($cursor > 0);
foreach($a as $f) {
echo $f ;
}
?>
Is there a better and simpler way of doing it? Where am i going wrong? help please?
API docs state this request is deprecated:
This method is deprecated as it will only return information about users who have Tweeted recently. It is not a functional way to retrieve all of a users followers. Instead of using this method use a combination of GET followers/ids and GET users/lookup.
Use this API instead: https://dev.twitter.com/docs/api/1/get/followers/ids
There should be a property in your object called next_cursor, as long as that's non-zero, keep doing the request again (specifying that cursor) until you get all the results.
I am using the "elastica" php client for ElasticSearch.
I'm a bit new to OO-programming, especially in php.
However, I have managed to search my elasticsearch server using the elastica php client and store the response in an "Elastica_ResultSet" object. I have had no luck accessing the contents of that object whatsoever.
I would like to be able to list the total number of results, find an elasticsearch record id of a result and get the full content of an elasticsearch record for that result.
The Elastica class reference can be found here http://ruflin.github.com/Elastica/api/index.html , although I don't know what to do with it.
Here is the php code I have been using to get this far:
<?php
function __autoload_elastica ($class) {
$path = str_replace('_', '/', $class);
if (file_exists('extentions/' . $path . '.php')) {
require_once('extentions/' . $path . '.php');
//echo "$path EXISTS!!!";
}
}
spl_autoload_register('__autoload_elastica');
// New ES Client
$client = new Elastica_Client();
// Set Index
$index = $client->getIndex('test1');
// Set Document Type
$type = $index->getType('user');
// Perform Search
$resultSet = $index->search('halo');
?>
So basicaly you can use var_export to output your resultset
But in general the elastica search returns a Elastica_ResultSet object which has several attributes you can use like count, totalHits facets and so on.
and also holds an array of Elastica_Result objects these can be accessed either by calling the Elastica_ResultSet getResults() method or by using the current() and next() methods or by simply using the php foreach function
The Elastica_Result the data of the results and also has several methods you can use.
getId(), getVersion(), getData() and so on.
// Set Document Type
$type = $index->getType('user');
// Perform Search
$resultSet = $index->search('halo');
// Get IDs
$resultIDs = array();
foreach($resultSet as $result){
$resultIDs[] = $result->getId();
}
I would like to let you know something that was a bit hard for me to get.
The query and the sorting of results
// Set the query terms for your search
$queryTerm = new Elastica_Query_Terms();
$queryTerm->setTerms('user', array("test", "test1"));
// Create the sorting array
$sort = array("user" => array("order" => "desc"));
// Create the query
$query = Elastica_Query::create($queryTerm);
// Set the sorting to the query
$query->setSort($sort);
// Perform the search
$resultSet = $index->search($query);
Hope this helps
After a couple of months OO practise, it seemed performing a simple var_dump($resultSet) would have provided me with the structure and contents of the returned object... can't believe that nobody made any suggestions for such a basic question ;)