PHP XML Problem – Hyphen in the Element Name

I have been playing with PHP and web services lately. As I did not learn PHP from the ground up, I just tried to assemble my code base upon the examples I gathered. One problem puzzled me for a long time. I didn’t figure out what the problem is until I rewrote the program in PowerShell.

I have used Simple XML to parse an XML document. There are multiple links in this document. I iterated the links array to print out the information. Problem is I can print out some elements, but not the others. For example, this works:

echo $link->description;

However, this does not work:

echo $link->link-code-html;

I worked on this particular problem for an afternoon, but I could not figure out what was wrong. It’s hard to debug using PHP, so I decided to use PowerShell to rewrite the program and see if I could replicate the same “error”.  I did get the same problem. In PowerShell, dot notation is used and I cannot print this, either:

echo $link.link-code-html

I later learned that the hyphen is interpreted as minus sign. I had to modify the the PowerShell code to:

echo $link.Item('link-code-html')

With this information in mind, I know the hyphen in the XML element name is the cause. The online manual for PHP SimpleXML has one  example. So, my original code has to be modified to

echo $link->{'link-code-html'};

HTA: Check Process Example

Microsoft has a less known technology called HTA (HTML Application). Basically, it gives scripts a GUI front end using HTML notation. I have known HTA for years, but I never get around to try it. While I was thinking about writing a script to check running processes on a computer, I thought it would be nice if I can write it using HTA. Here is my experiment.

As a system administrator, I often need to check user’s machine for malicious programs. The manual process is like this. I open up Task Manager and look for anything I am not familiar. When I identify those suspicious processes, I then open up a web browser to check the processes. The two sites I use regularly are ProcessLibrary.com and Google. I need to enter the process name manually and the whole process is tedious.

The idea is this, I want to write a simple script to list all processes running on a computer. I want to present the results in an HTML table with links to ProcessLibrary and Google. If I need to check a particular process, I just click the corresponding link without manually entering the process name.

Before I began writing the script, I found one script from ScriptingGuys on MSN groups. The original script shows processes running on a local computer. I modified it so that it can check remote computers and I also added links to find process information on ProcessLibrary.com and Google.

Here is the link to the script. Check Process HTA script WordPress.com doesn’t allow upload of .hta file, so the file was uploaded as a word document file with .doc extension. Click the link and save the file as checkprocess.doc . Then change the name to checkprocess.hta , and you are ready to try it.

To run it, double click on the file just like the other applications. It brings up a window like this.

processcheck1.jpg

 

You can enter a remote computer name in the text box, or you can just click the Run Script button to check the local computer. It then fill out the lower part of the window with processes.

processcheck2.jpg

To check a particular process information, click on the Search links next to it. The application would bring up a browser with the search results.

processcheck3.jpg

PowerShell Example for Checking PS3 Availability on Amazon

I used a PowerShell script to check price of Garmin i3 on Amazon. It’s very easy to modify it to check the availability of PS3. When the PS3 is not available, the price from the query is $0.00. So, if the price is greater than 0 that means it’s available. The script then prepares an email with a link to purchase it.

You need to change the SMTP server name ($smtpserver), your email address ($email) and AWSAccessKeyId ($awskey). If you don’t know how to get an AWSAccessKeyId, you can check out my original post for the Garmin i3. The default is to check the model with 60GB HD. Uncomment the second $asin to check the model with 20GB HD.

Once you test the script with your changes, use your favorite scheduler to check availability routinely.

# Script for checking PS3 on Amazon
$smtpserver = "smtp.nospam.com"



$email = "someone@nospam.com"



$awskey = "YOUR-AWSAccessKeyId"



$asin = "B0009VXAM0" #60GB



#$asin = "B000IZWNLG" #20GB
$url =  "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService"



$url += "&AWSAccessKeyId=" + $awskey



$url += "&Operation=ItemLookup"



$url += "&ItemId=" + $asin



$url += "&ResponseGroup=Offers"



$rxml = [xml](new-object Net.WebClient).DownloadString("$url")



$price =  $rxml.ItemLookupResponse.Items.Item.Offers.Offer.OfferListing.Price.Amount



$price = $price/100



if ($price -gt 0) {



    $textbody = "Playstation 3 is now $" + $price + " at Amazon "



    $textbody += "http://www.amazon.com/exec/obidos/ASIN/" + $asin + "/animereviews-20/ref=nosim"



    $smtp = new-object Net.Mail.SmtpClient($smtpserver)



    $smtp.send($email, $email , "PS3 Available at Amazon!", $textbody)



}

PowerShell and Amazon Web Service

I got some experiences with Amazon Web Service when I created my Anime Reviews site. It’s pretty neat that you can write a query to look up very detailed product information. Recently, I am thinking to buy a Garmin StreetPilot i3 from Amazon.

i3.jpg

The regular price is around $308.00, but I heard that sometimes Amazon would lower the price to as low as $199.00. However, the low price is only available for a short time. I don’t want to sit in front of my computer and manually check the price myself. Wouldn’t it be nice if I can have a script to check the price automatically? It would be nicer if I write the script using PowerShell!

Ok, enough rambling. Let’s get started. To use Amazon Web Service, the first thing to do is to create an account and obtain your own Access Key ID. You can create a free account here.

After the account has been created successfully, you can log on to the site with your new account. Move the mouse cursor on top of the button that says “Your Web Services Account”. A drop down menu would appear, click “View Access Key Identifiers”. There are two keys, one is called “Access Key ID”, the other is called “Secret Access Key”. Make a note of the Access Key ID, this is the key you used for the web service. The next step is sending the Secret Access Key to me. :-) Ok, just kidding. You should NOT share Secret Access Key with anyone, it’s only used to create signature. You should keep it confidential and not reveal it to anyone.

Amazon Web Service offers several ways to find product information. ItemSearch is used to search products by using keywords. Since we already know the product that we are interested in, we can just use ItemLookup. To use ItemLookup, you need two pieces of information, AWSAccessKeyId and ItemId. You already have the Access Key ID, all you need to know is the ItemId for the product. Each product offered on Amazon has a unique ID. If you look at a product page, it’s called ASIN. You use ASIN as ItemId for the query. For books query, use ISBN as ItemId in your query. This is the query string for looking up information for the Garmin i3.

$url =  "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService"

$url += "&AWSAccessKeyId=Your_AccessKeyID_Here"

$url += "&Operation=ItemLookup"

$url += "&ItemId=B000ACHVVE"

$url += "&ResponseGroup=Offers"

Note that this is for North America www.amazon.com. If you want to query product information for other Amazon sites. You need to change the first line accordingly. You can check here for information on how to modify the query string. Another point to note is that if you don’t specify ResponseGroup in your query, the default response is “Request” and “Small” which don’t have the price information. To get the current price, we use “Offers” as response group. Finally, we use .Net’s Net.WebClient class to get the response from Amazon Web Service. The response from the server is an xml string. We can cast it to XMLDocument for easy accessing the data. The amount returned from the query is in cents, so divide it by 100 to get the dollar amount.

$rxml = [xml](new-object Net.WebClient).DownloadString("$url")

$price =  $rxml.ItemLookupResponse.Items.Item.Offers.Offer.OfferListing.Price.Amount

$price = $price/100

echo $price

You might ask how did you come up with the offer price? You can check the documentation in Amazon Web Service web site, or you can save the response as an XML file and use your favorite XML editor/reader to examine the response. FireFox is just fine to parse the XML file.

$sxml = (new-object Net.WebClient).DownloadString("$url")

echo $sxml > "c:\\response.xml"

I tested the script under Vista Beta 2 and it works well.

MSH is now Microsoft PowerShell

I haven't played with Monad shell for a while, the next thing I know there is a new scripting language called "Microsoft PowerShell". At first, I thought it's a brand new language, but actually they renamed Monad and made it PowerShell.

After installation, I tried to run one of my earlier Monad scripts. Just like the previous updates of Monad, the default execution policy is "Restricted". Under this policy, you can use PowerShell interactively. No scripts are allowed. If you like to run your own scripts without signing, you need to change the execution policy. Now there is a cmdlet to change policy without using regedit. Here is the cmdlet to change the policy to RemoteSigned.

Set-ExecutionPolicy RemoteSigned

WQL and Path

I am playing around with WQL today. For a longest time, I couldn’t get this query to work.

Set colFiles = objWMIService.ExecQuery ("SELECT * FROM CIM_DataFile" &  _

   " WHERE Drive = 'c:' AND Extension = 'mdb' And Path = '\\windows\\' ")

Have you noticed anything wrong with the query? It’s the Path! I found that you need to use double back slash instead of single back slash. So, the correct Query should be like this.

Set colFiles = objWMIService.ExecQuery ("SELECT * FROM CIM_DataFile" &  _

   " WHERE Drive = 'c:' AND Extension = 'mdb' And Path = '\\\\windows\\\\' ")

Also, I found that if you have “!=” in your query, the query runs very very slowly.

How to Create a Hyperlink in Excel Spreadsheet Using VBScript

Someone at the newsgroup asked this question. This is the VBScript that I wrote to accomplish this.

Dim objExcel

Set objExcel = WScript.CreateObject("Excel.Application")



objExcel.Visible = TRUE

objExcel.Workbooks.Open "C:\\bintest.xls"

objExcel.Workbooks(1).Activate

objExcel.Workbooks(1).Worksheets(1).Range("A1").Select



Dim sLinkAddress

sLinkAddress = "http://www.google.com"



objExcel.Workbooks(1).Worksheets(1).Hyperlinks.Add _

    objExcel.Selection, sLinkAddress

objExcel.Workbooks(1).SaveAs "C:\\bintest.xls"

objExcel.Quit



set objExcel = nothing

VB Script wrapper function for regular expression

Function Found(strTarget, strPattern)

  Dim regEx

  Set regEx = New RegExp

  regEx.Pattern = strPattern

  regEx.IgnoreCase = False

  Found = regEx.Test(strTarget)

  set regEx = Nothing

End Function

WMI script to find files last accessed on a certain date

dtDate = "5/2/2005"

strSearchFolder = "C:Windows"



Set objFSO = CreateObject("Scripting.FileSystemObject")

WScript.Echo "File(s) last accessed on: " & dtDate & " in: " & strSearchFolder

EnumAndCheckFiles objFSO.GetFolder(strSearchFolder), dtDate



Sub EnumAndCheckFiles(objFolder, dtDate)

    Set objFiles = objFolder.Files

    For Each objFile in objFiles

    CheckFile objFile, dtDate

    Next

    For Each objSubfolder in objFolder.SubFolders

        EnumAndCheckFiles objSubfolder, dtDate

    Next

End Sub



Sub CheckFile(objFile, dtDate)

    If DateDiff("d", objFile.DateLastAccessed, dtDate) = 0 Then

        WScript.Echo objFile.Path

    End if

End Sub

Translator

English flagItalian flagKorean flagChinese (Simplified) flagChinese (Traditional) flagPortuguese flagGerman flagFrench flagSpanish flagJapanese flagArabic flagRussian flagGreek flagDutch flagBulgarian flagCzech flagHindi flagRomanian flagSwedish flagHebrew flagHungarian flag

Archives