conditional check inside a foreach is causing errors - php

I am using Simple_html_dom trying to grab Reputation points and make a check on those values and then extract only those user profiles whose Repu is greater that 200. Below is the code, It works fine when doing this
`
$html2=str_get_html($html1);
foreach ($html2->find('.user-details') as $value) {
foreach($html2->find('.reputation-score') as $repu){
echo (int)$repu->plaintext.$value.'<br>';
}
}
When doing the above i am getting all thereputation and the user detailswell each line, looks fine till now. But now i wanna perform aconditional checkand then echo only those profiles whose repo is higher than100`. So when i am trying the below code
`
$html2=str_get_html($html1);
foreach ($html2->find('.user-details') as $value) {
foreach($html2->find('.reputation-score') as $repu){
if($repu>100)
{
echo ($repu->plaintext.$value.'<br>';
}
}
}
I am getting an error saying Object of class simple_html_dom_node could not be converted to int seeing that i've tried doing (int) to convert and then echo still couldnt solve
Any help here ?

Related

how to show multiple photo twitter status using php

i need to display/show photo with twitter api, but i have only get 1 photo
$results = $toa->get('https://api.twitter.com/1.1/statuses/show.json?id=xxxxxxxxxxxx' );
if (isset($results->entities->media)) {
foreach ($results->entities->media as $media) {
$media_url = $media->media_url; // Or $media->media_url_https for the SSL version.
}
}
echo $media_url;
this code get only 1 photo ,how to get pulling multiple image (max 4) on 1 twitter status ?
thank
It looks like you're overwriting the $media_url variable on each loop. You would want to loop through the $results->entities->media variable when displaying the images like this:
foreach ($results->entities->media as $media) {
echo '<img src="'.$media->media_url.'"/>';
}
I don't know too much about the Twitter API however you are only getting one photo at the end because you are doing this.
Inside the loop you keep updating $media_url to $media->media_url. Then outside the loop you echo $media_url only once.
All you are doing is changing that one variable over and over, you need to have your echo statement inside the loop.
if (isset($results->entities->media)) {
foreach ($results->entities->media as $media) {
$media_url = $media->media_url;
echo $media_url;
}
}
Like I said I don't have too much knowledge of the Twitter API but providing your loop is working to get one of the images then moving the echo statement inside the loop should help.

How to move an eDirectory entry via php?

I have this ldap entry:
cn=blah,ou=apples,ou=people,dc=yay,dc=edu
I need to move that entry to:
cn=blah,ou=oranges,ou=people,dc=yay,dc=edu
My scripts are all PHP so I've been trying to use php.net/ldap_rename
ldap_rename($connection, "cn=blah,ou=apples,ou=people,dc=yay,dc=edu", "cn=blah", "ou=oranges,ou=people,dc=yay,dc=edu", true);
Does not work. It returns false.
This http://us2.php.net/manual/en/function.ldap-rename.php#82393 comment mentions that eDirectory wants to leave the parent as NULL. Like:
ldap_rename($connection, "cn=blah,ou=apples,ou=people,dc=yay,dc=edu", "cn=blah", NULL, true);
That returns TRUE but does not actually move the entry. Not surprising since it's not changing the parent... I'm sure it could change the cn=blah to something else...
I have thought of deleting the entry and recreating it. But that's a painful way to go about it. Writing out and running a LDIF file would also be painful.
So, how do I move an entry from one OU to another, in php, without the pain of my other two options?
What I'm running:
Ubuntu 12.04 LTS
PHP 5.3.10
eDirectory 8.8 is on SLES 11
Edit
So, I found this:
The modrdn change type cannot move an entry to a completely different subtree. To move an entry to a completely different branch, you must create a new entry in the alternative subtree using the old entry's attributes, and then delete the old entry.
From http://www.centos.org/docs/5/html/CDS/ag/8.0/Creating_Directory_Entries-LDIF_Update_Statements.html
I found a couple other pages with similar statements.
So it sounds like I have to make a new entry, copying the attributes, the delete the old one. Like the second painful option I mentioned above.
Well, I ended up using the "create new entry, delete old one" method. I still think I had another way working a while back, but I can't remember what. So here's a basic move function.
function move($connection, $ldapEntryReference, $new_dn){
//First, get the values of the current attributes.
$attributes = array(); //start attributes array
$firstattr = ldap_first_attribute($connection, $ldapEntryReference);
$value = ldap_get_values($connection, $ldapEntryReference, $firstattr);
$attributes[$firstattr] = $value;
while($attr = ldap_next_attribute($connection, $ldapEntryReference)) {
if (strcasecmp($attr, 'ACL') !== 0) { //We don't want ACL attributes since
//eDir/ldap should deal with them for us.
if (strcasecmp($attr, 'jpegPhoto') === 0) {
//binary values need to use the ldap_get_values_len function.
$value = ldap_get_values_len($this->connection, $ldapEntryReference, $attr);
} else {
$value = ldap_get_values($this->connection, $ldapEntryReference, $attr);
}
$attributes[$attr] = $value;
}
}
//Create a new entry array with the values.
$entry = array(); //start entry array.
foreach($attributes as $key => $value) {
foreach($value as $key2 => $value2) {
if (strcasecmp($key2, 'count') !== 0) {//get rid of 'count' indexes
//ldap_add chokes on them.
$entry[$key][$key2] = $value2;
}
}
}
//Add the new entry.
if (ldap_add($connection, $new_dn, $entry)) {
//Delete the old entry.
if (ldap_delete($connection, ldap_get_dn($connection, $ldapEntryReference)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
Hopefully this helps someone, sometime.
There actually isn't a need to recreate in eDir. Doing a recreate causes problems in an environment that runs IDM as the object will have a new GUID and the IDM engine will not see the event as a true "move".
The following code moves users fine (tested eDir 8.8.x & eDir 9.x):
$olduserdn = "cn=userid,ou=container1,o=org";
$newdestdn = "ou=container2,o=org";
if (preg_match('/^(cn=[A-Za-z0-9]+)\,(.+)/i', $olduserdn, $rdnmatches))
{
if (ldap_rename($ldapconn, $olduserdn, $rdnmatches[1], $newdestdn, TRUE))
{
print("Moved $olduserdn to $rdnmatches[1],$newdestdn");
}
else
{
print("Failed move because " . ldap_error($ldapconn));
}
}
Don't forget to give a bit of time for replication...
Also consider constraints around modifying/moving objects that are still being replicated from a previous move event.
Try this:
ldap_rename($ldapconn, "cn=blah,ou=apples,ou=people,dc=yay,dc=edu", "cn=blah", "ou=oranges,ou=people,dc=yay,dc=edu", true);

PHP arrays within arrays in session

I've been using PHP for a little bit, but only doing basic tasks, and have gotten stuck while trying to build part of a knowledgebase.
While creating an article, you can upload screenshots - these need to be stored in a staging area until the article is saved, and I've got their information saved into the users session.
In POST upload:
...
$new_ss = array();
$new_ss['display_name'] = $ss_name;
$new_ss['server_path'] = "../uploads/"; /* outside of doc root */
$new_ss['server_path'] .= hash_file('md5', $ss_tmp_name) . "_" . $ss_name;
if ( #move_uploaded_file($ss_tmp_name, $new_ss['server_path']) )
{
$_SESSION['article']['screenshots'] .= $new_ss;
...
Then trying to display the upload to the user within the editing page:
if ( is_array($_SESSION['article']['screenshots']) && count($_SESSION['article']['screenshots']) > 0 )
{
echo "<table border=\"1\">\n";
foreach ( $_SESSION['article']['screenshots'] as $ss )
{
... display table of uploaded images ...
The trouble is, PHP isn't seeing $_SESSION['article']['screenshots'] as an array - and I can't see why.
After following the answer here:
PHP foreach() with arrays within arrays? I tried quickly doing the following:
function print_array($key, $item) {
echo "$key -> $item\n";
}
...
{
$_SESSION['article']['screenshots'] .= $new_ss;
array_walk_recurisve($_SESSION['article']['screenshots'], 'print_array');
...
however I get the error "expects parameter 1 to be array, string given".
If I do an 'error_log($_SESSION['article']['screenshots']);' it just prints "Array" for however many images are uploaded, and print_r just printed '1' by itself.
Can someone shed some light please?
Well I'm not really sure which of your key should be an array, in this line:
$_SESSION['article']['screenshots'] .= $new_ss;
You're making it a string by concatenating it. If you want to append as an array, you should probably do this:
$_SESSION['article']['screenshots'][] = $new_ss;

MongoDB showing error when it finds a blank entry

I have a project where it searches for a specific entry in a specific column and then returns all documents that have that entry in that column. It works almost perfectly except when that entry field is empty it gives an error. Let me try to illustrate below.
My DB:
A|B|C|D
1|1|5|5
2|1| |6
3|2|7|7
4|2|8|8
My PHP:
$query = array( "B" => 1);
$cursor = $collection->find( $query );
foreach ($cursor as $obj) {
echo $obj["A"] . $obj["B"] . $obj["C"] .$obj["D"] . "<br />";
}
My output is:
1155
21Notice: Undefined index: C6
How do I go about not giving any errors. Just treat it as an empty field. I'm not sure if this is a common problem but, I'm still new to PHP and very new to MongoDB.
Use isset() to find out if the key exists in the array before trying to index using it
foreach ($cursor as $obj) {
echo $obj["A"] . $obj["B"]. (isset($obj["C"]) ? $obj["C"] : '' ) .$obj["D"]."<br />";
//It will replace each blank with an ''
}
I believe thats nothing to do with mongodb. Its how the flexible document schema works. It wont return the field because the key C doesnt exist in the particular document.
I dont have any experience with PHP. But am sure php throws the error because you are trying to access the key 'C' that doesnt exist in the particular document.
But i believe these problems can easily be solved if you use some ODM (Object document mappers). It solves the problem by assigning default value based on the data type of the field.
Hope it helps

Problems using the Amazon API to search ISBN

I'm having a few issues using the amazon API to search for ISBN.
The code seams to work for a FEW isbn's and returns some results however the majority of books (mainly factual/reference books) I search for via ISBN return no results.
To test I am getting the ISBN-10 number from amazon. I have also then tested by searching for this isbn through their own search.
This is the code we use to get the results.. I dont suppose anyone can spot a flaw?
function getBooks($isbn){
$client = new AmazonECS('AWS_API_KEY', 'AWS_API_SEECRET_KEY', 'co.uk', 'tutorp-21');
$response = $client->responseGroup('Small,Images,EditorialReview')->category('Books')->search($isbn);
$books = array();
if($response->Items->TotalResults > 1){
foreach($response->Items->Item as $item)
$books[] = parseItem($item);
}else if($response->Items->TotalResults == 1){
$books[] = parseItem($response->Items->Item);
}
return $books;
}
Cheers
Edit : Just to clarify... The problem we are facing is that only some ISBN numbers return results. Even though these books exist in Amazon they dont seam to return any results when searched through the API
Without looking into the AmazonECS API, I'd expect TotalResults of 1 to return an array containing a single item still; the assignment in your else clause via parseItem($response->Items->Item) will fail accordingly (i.e. books[] remains empty), because $response->Items->Item is still an array and cannot be parsed into an item.
Consequently you should drop the else clause and adjust your condition to test for 0 instead (or >= 1 of course), e.g.:
// [...]
if($response->Items->TotalResults > 0){
foreach($response->Items->Item as $item)
$books[] = parseItem($item);
}
// [...]
Update
The Show first 10 results example of the Amazon ECS PHP Library confirms my expectations, the result loop is implemented like so:
//check that there are items in the response
if (isset($response['Items']['Item']) ) {
//loop through each item
foreach ($response['Items']['Item'] as $result) {
// [...]
}
}
The problems was books that didn't have editorials. The code written works fine but needed exceptions for books being returned without all the information.

Categories