Can't get destination URL of Ad by Adwords API - php

I want to get the destination URL by using Google Adwords API(v201509).
Cording with PHP.
In the following code, I'm trying to get the url by using 'get' method of AdGroupAdService.
As a result, I could get ad->displayUrl properly but couldn't get ad->url and ad->finalUrls (null given).
What am I doing wrong?
adwords.php with the following code -
$adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);
// Create selector.
$selector = new Selector();
$selector->fields = array('Headline', 'Id');
$selector->ordering[] = new OrderBy('Headline', 'ASCENDING');
// Create paging controls.
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
do {
// Make the get request.
$page = $adGroupAdService->get($selector);
// Display results.
if (isset($page->entries)) {
foreach ($page->entries as $adGroupAd) {
array_push($googleAccountStructure, $adGroupAd);
//var_dump($adGroupAd);
}
}
// Advance the paging index.
$selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
} while ($page->totalNumEntries > $selector->paging->startIndex);

Please update your selector fields with this one
$selector->fields = array('Headline', 'Id', 'CreativeFinalUrls', 'Url');
As per adwords api doc if you use Upgraded URLs you need to pass Final URLs in selector fields
https://developers.google.com/adwords/api/docs/reference/v201509/AdGroupAdService.Ad#finalUrls

Related

Navigating forms and grabbing DOM-Elements from a website using Guzzle/Goutte (PHP, Debugging)

I'm fairly new to PHP and playing around with Goutte/Guzzle to grab some basic information from a website after filling out a few forms.
However I have problems finding issues (there might be a ton of them) since I could not find a way to display or console log any of the results or problems. The script finishes with Code 0 but does not return anything. A tip on how to print out what is currently stored in $client would already go a long way.
Here is the whole code I'm trying to run with a bunch of comments for clarification. I'm sorry for using such a large block, but any of this could have issues.
<?php
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
class grabPlate
{
// WKZ
public function checkPlate
{
$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
'cookies' => true,
'timeout' => 60,
));
$goutteClient->setClient($guzzleClient);
$crawler = $goutteClient->request('GET', 'https://kfz-portal.berlin.de/kfzonline.public/start.html?oe=00.00.11.000000');
//Click the first "Start" in the top left
$link = $crawler
->filter('a:contains("Start")')
->eq(0)
->link()
;
$crawler = $client->click($link);
//Check checkbox, fill in name and press the button
$buttonCrawlerNode = $crawler->selectButton('Weiter');
$form = $buttonCrawlerNode->form();
$form['gwt-uid-1']->tick();
$form['select2-hidden-accessible']->select('Herr');
$form['gwt-uid-4'] = 'John';
$form['gwt-uid-5'] = 'Doe';
$client->submit($form);
//Fill some Data into the forms and search
$buttonCrawlerNode = $crawler->selectButton('Button-3616');
$form = $buttonCrawlerNode->form();
$form['.kfzonline-KennzeichenGrossEb'] = 'AB';
$form['.kfzonline-KennzeichenGrossEn'] = '123';
$client->submit($form);
//Extract collection
$info = $crawler->extract('.collection');
//return 1 if something is inside collection, 0 if it's empty
if($info == NULL) {
return 1;
} else {
return 0;
}
}
}
?>
As I said just running the script in PHPStorm returns the status 0. However when plugging it into an API and accessing it, I get a server timeout response.
You should either use a Debugging. Install xDebug to do so in PHP. This is also easy to integrate into Phpstorm.
Alternatively use var_dump() for printing out debug information about variables of any type to console.
You can display the requested page inside your php page, you have to add this snippet :
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.facebook.com/');
echo $res->getBody();

Facebook API, PHP SDK getRequestForNextPage()

i'm developing a web app (with PHP SDK) that basically take user posts of last year and do some kind of analysis on it.
Untill now i used to load the data with a recursive function that everytime get the content from the paging link and call itself again with that data.
i've just discovered that i can use getRequestForNextPage(); so im tring to use this function but i got some troubles , seems that getRequestForNextPage() do not respect request's parameters. I know my explanation is pretty confused, here a simplified version of my code:
$thedate= strtotime('now ,-1 year');
$today = strtotime('now');
$richiesta ="/me/posts?since=".$thedate."&until=".$today;
$request = new FacebookRequest( // richiedo i miei statuses
$session,
'GET',
$richiesta
);
$respons = $request->execute();
function looper($response){
$graphObject = $response->getGraphObject();
$nextPageRequest = $response->getRequestForNextPage();
$respy = $nextPageRequest->execute();
$x = $graphObject->getProperty('data');
$y = $x->asArray();
$counter = 0 ;
foreach ($y as $el){
//do something
}
if ( $respy != false ){
looper($respy);
} else {
return;
}
}
looper($respons);`
it seems that that function just keep to iterate even if the posts are older than 1 year.
do getRequestForNextPage() just dont care about request parameters? it just check if there is a "next" paging link in the graph object? Thanks in advance for any suggestion

How to generate entity id for GAE datastore in php?

i am trying to insert new entity using PHP client library into datastore, i am using datastore_connect.php file from this example, https://github.com/amygdala/appengine_php_datastore_example
I want to insert entity with auto id, not the name. I see that there is function setId(), but i dont know how to generate proper id. Whats the best practice in doing so?
Thanks
function createKeyForTestItem () {
$path = new Google_Service_Datastore_KeyPathElement();
$path->setKind("testkind");
$path->setName("testkeyname");
//$path->setId(??)
$key = new Google_Service_Datastore_Key();
$key->setPath([$path]);
return $key;
}
You can have Cloud Datastore generate the ID for you by populating the insertAutoId field on the mutation instead of the upsert field.
Here's a code snippet (adapted from the datastore_connect.php file you posted):
function create_key() {
$path = new Google_Service_Datastore_KeyPathElement();
$path->setKind("testkind");
// Neither name nor ID is set.
$key = new Google_Service_Datastore_Key();
$key->setPath([$path]);
return $key;
}
function create_entity() {
$entity = new Google_Service_Datastore_Entity();
$entity->setKey(create_key());
// Add properties...
return $entity;
}
function create_commit_request() {
$entity = create_entity();
$mutation = new Google_Service_Datastore_Mutation();
$mutation->setInsertAutoId([$entity]); // Causes ID to be allocated.
$req = new Google_Service_Datastore_CommitRequest();
$req->setMode('NON_TRANSACTIONAL');
$req->setMutation($mutation);
return $req;
}
If you're looking for a PHP library to take away most of the headache of Cloud Datastore, you could try my new library, which sits on top of the official google-api-php-client:
https://github.com/tomwalder/php-gds
And here's a sample code snippet to create an Entity with an auto-generated ID
$obj_book = new GDS\Entity();
$obj_book->title = 'Romeo and Juliet';
$obj_book->author = 'William Shakespeare';
$obj_book->isbn = '1840224339';
// Write it to Datastore
$obj_book_store->upsert($obj_book);
More code snippets and documentation on GitHub.

PHP DOMDocument - trouble accessing list index

I am writing some code for an IRC bot written in php and running on the linux cli. I'm having a little trouble with my code to retrieve a websites title tag and display it using DOMDocument NodeList. Basically, on websites with two or more tags (and you would be surprised how many there actually are...) I want to process for only the first title tag. As you can see from the code below (which is working fine for processing one, or more tags) there is a foreach block where it iterates through each title tag.
public function onReceivedData($data) {
// loop through each message token
foreach ($data["message"] as $token) {
// if the token starts with www, add http file handle
if (strcmp(substr($token, 0, 4), "www.") == 0) {
$token = "http://" . $token;
}
// validate token as a URL
if (filter_var($token, FILTER_VALIDATE_URL)) {
// create timeout stream context
$theContext['http']['timeout'] = 3;
$context = stream_context_create($theContext);
// get contents of url
if ($file = file_get_contents($token, false, $context)) {
// instantiate a new DOMDocument object
$dom = new DOMDocument;
// load the html into the DOMDocument obj
#$dom->loadHTML($file);
// retrieve the title from the DOM node
// if assignment is valid then...
if ($title = $dom->getElementsByTagName("title")) {
// send a message to the channel
foreach ($title as $theTitle) {
$this->privmsg($data["target"], $theTitle->nodeValue);
}
}
} else {
// notify of failure
$this->privmsg($data["target"], "Site could not be reached");
}
}
}
}
What I'd prefer, is to somehow limit it to only processing the first title tag. I'm aware that I can just wrap an if statement around it with a variable so it only echos one time, but I'm more looking at using a "for" statement to process a single iteration. However, when I do this, I can't access the title attribute with $title->nodeValue; it says it's undefined, and only when i use the foreach $title as $theTitle can I access the values. I've tried $title[0]->nodeValue and $title->nodeValue(0) to retrieve the first title from the list, but unfortunately to no avail. A bit stumped and a quick google didn't turn up a lot.
Any help would be greatly appreciated! Cheers, and I'll keep looking too.
You can solve this with XPath:
$dom = new DOMDocument();
#$dom->loadHTML($file);
$xpath = new DOMXPath($dom);
$title = $xpath->query('//title')->item(0)->nodeValue;
Try something like this:
$title->item(0)->nodeValue;
http://www.php.net/manual/en/class.domnodelist.php

I'm trying to scrape a specific div with an id on a page

I want to scrape the contents of a page, well really just a single div from that page, and display it to the user inside of a small div on a webpage. I just need a piece of info from a carfax page that needs user credentials so I can't post the exact code but I tried using google.com and have the same problem so the solution should cross over.
Right now I've tried this:
$webPage = file_get_contents('http://www.google.com');
$doc = new DOMDocument();
$doc->loadHTML($webPage);
$div = $doc->getElementById('lga');//this is the id to the div holding the image above the textbox
//echo $webPage;//this displays www.google.com minus the image. I imagine because of the file path
//var_dump($div);//this display "object(DOMElement)#2 (0) { }" and I'm not sure what that means
//echo $div;//this has a server error
I'm also looking at simple_html_dom.php trying to figure that out.
You can use this:
/**
* Downloads a web page from $url, selects the the element by $id
* and returns it's xml string representation.
*/
function getElementByIdAsString($url, $id, $pretty = true) {
$doc = new DOMDocument();
#$doc->loadHTMLFile($url);
if(!$doc) {
throw new Exception("Failed to load $url");
}
// Obtain the element
$element = $doc->getElementById($id);
if(!$element) {
throw new Exception("An element with id $id was not found");
}
if($pretty) {
$doc->formatOutput = true;
}
// Return the string representation of the element
return $doc->saveXML($element);
}
// call it:
echo getElementByIdAsString('http://www.google.com', 'lga');

Categories