Parse an XML webpage using PHP - php

How do I use PHP to parse XML on the web?
Here is the example XML. How would you get the value of the first "AskRealtime"?
I am aware of SimpleXML. I am looking for the proper code to open the XML webpage, and work with it using SimpleXML.
This suggested code does not succesfully load the page:
$xml = #simplexml_load_file("http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20AskRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22A%22%2C%22AA%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
$price = $xml->results->quote[0]->AskRealtime;
echo $price;

Have you tried using SimpleXMLElement? It works just like your code but it's constructed differently.
$url = 'http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20AskRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22A%22%2C%22AA%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
$xml = new SimpleXMLElement($url, null, true);
echo $xml->results->quote[0]->AskRealtime;
There are different methods for getting the file contents, even though I doubt it's the problem.
/* cURL */
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($curl);
curl_close($curl);
/* Alternative */
$contents = file_get_contents($url);
Can you tell what is the error you get? Or try var_dump($xml) and see what it returns.

Step 1. - load the file in SimpleXML $xml = #simplexml_load_file($fl) or die($errorMsg);where $fl is the file URL and $errorMsg is the error message to display.
Step 2. - get a content $whatever=$xml->results->quote->AskRealtime[0]; Explained: it goes to the XML, then what is named "results", then what is named "quote", then what is named AskRealtime, but the first (index 0) of it.
And a note: if, for some reason, you'll have to get something which is named whatever-else (so it has a - in the name), then it works only if you make the code $xml->{'whatever-else'}

Use can use some HTTP request library to get the file, e.g.: http://www.php.net/manual/en/function.http-get.php
Then feed the response to SimpleXML.

Related

How to check if it is a xml file or a json file in PHP

How i can check in php if the url contains xml of json file.
so in the $url holds the url and than it should check whethere it is a xml file or a json file.
$url = 'http://hello.asdasd/asdasd/asdasd';
if (($url == JSON) = TRUE){ // how to check it is a json file, do the follwing action
$xml = file_get_contents($url);
$json = json_decode($xml, true);
}
else if ($url == XML) = TRUE){ // how to check it is a XML file, do the follwing action
$xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA);
}
Any advice will be really appreciable.
Simple process:
Attempt to decode it as JSON
Check for errors
Attempt to load it as XML
Check for errors
You have most of this code already, just adjust your if statements to check the results of attempting to decode/load the data.
Also since it's a web resource, you could cross-check the mime type. This would require using something other than file_get_contents().
I would suggest using the solution for checking a file is valid Json.
Then you simply check if the string is JSON then assume XML - if it's guaranteed to be one or the other!

SimpleXMLElement:difference in Curl and file_get_contents

So guys, there is another question.
I've fetched a webpage via curl and constructed XML document:
.......
$data = curl_exec($ch1);
$xml = new SimpleXMLElement($data);
And it worked correctly.
After I used file_get_contents like this
......
$file1 = file_get_contents('https://meet77842937.adobeconnect.com/api/xml?action=report-my-meetings', false, $context);
$xml = new SimpleXMLElement($file1);
The last code cannot construct XML, though I able to see through var_dump that it receives a page. And I stumbled: I think curl is advanced version of file_get_contents but they must not differ in fetching page. Where are the problems?
The error:Extra content at the end of the document
I don't know how but webpage returns some symbol at the end
With regards

Simulating a browser HTTP request method using CURL API in PHP

This is very basic, but I am kind of confused where I am going wrong (learning how to implement a RESTful Web Service). The context is, I have a simple simulator.php file that simulates an HTTP request to one of my local PHP files. The local PHP file (index.php) does nothing but return a variable with a value. So it's pretty much like this:
<?php
$variable = 'hello';
return $variable;
?>
and my simulator.php file has the following:
?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/kixeye/index.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
var_dump($contents);
curl_close($ch);
?>
However, var_dump($contents) does not quite spit out the value of $variable which is being returned from index.php. I don't quite understand why not.
returning something outside of a function won't actually do anything. The cURL request you are making will return the HTML response from the requested page, so what your really want to do is echo the response rather than using return.
Just change the index.php script to this:
<?php
$variable = 'hello';
echo $variable;
?>
And your var_dump() in the second script will output hello.
The $contents variable will contain the web page being returned by the http request done with Curl. If you only need one value from index.php, just echo it, and its value will end up in $contents as a string.
If you want to retrieve several variables, you could try json encode them and then echo the result in index.php. Then you would have to do the reverse in your second script by json decoding $contents.
Alternatively, you could generate and echo valid php code in the first script, and then eval it in the second, but this is very bad practice (the use of eval is strongly discouraged).
See:
json_encode
eval

Parsing iTunes json, then displaying it on webpage, and caching it with PHP

I'm working on a project where I need to get info from iTunes, cache it, and display it on a webpage with PHP. I prefer to use curl, since it seems faster, but I'm more familiar with get_file_contents. An example of the json url is http://itunes.apple.com/lookup?id=284910350. I'm able to grab and decode it, but I'm having trouble from there.
Here's my start:
<?php
$cas = curl_init('http://itunes.apple.com/lookup?id=284910350');
curl_setopt($cas, CURLOPT_RETURNTRANSFER, 1);
$jsonitunes = curl_exec($cas);
curl_close($cas);
$arr = json_decode($jsonitunes,true);
foreach($arr as $item) {
echo "kind: ". $item['kind'] ."<br>";
}
?>
I can print the array, or var_dump it, but can't seem to grab any values. After that, I need to cache the whole thing. If possible, I'd like to set it up to grab new content when it arrives, or on a frequent schedule without weighing down the server.
PHP Notice: Undefined index: kind in /var/www/html/frank/scratch.php on line 9
That should be your first clue (make sure you're logging notices somewhere where you can see them as you work). When you see that, you know you're referencing the array incorrectly.
Your next step should be
var_dump($arr);
to see where the key you're looking for actually is.
Then you should see that you actually need
foreach($arr['results'] as $item) {
Have you tried the json_decode function? You should be able to use cURL to download the contents of that page, store it in a variable, then use json_decode.
<pre>
<?php
$ch = curl_init("http://itunes.apple.com/lookup?id=284910350");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
$jsonDecoded = json_decode($content, true);
echo $jsonDecoded['results'][0]['artistName'];
?>
</pre>

API related with XML?

Is it done correctly? I am still confused with how api works. I am newbie. I have gone around google to find answers. I followed tutorial and tried to modify it. It is basic one.
I would like to retrieve the images of products which is on sale (mode=hot) for slideshow. I will appreciate the help if you could help me to understand how api shld be done.
EDIT
I am trying to pull the images from database in pinnacle cart. so i wanted to list out what it have in xml. All xml you see below is on source view but not on webpage itself, is it normal? Also when I am trying to show the images on webpage and the images don't appear. I am not sure where I went wrong.
<Product>
<Price><![CDATA[695.00000]]></Price>
<Visible><![CDATA[Yes]]></Visible>
<Taxable><![CDATA[Yes]]></Taxable>
<Weight><![CDATA[0.00]]></Weight>
<UPC><![CDATA[]]></UPC>
<Sku><![CDATA[]]></Sku>
<Title><![CDATA[Necklace]]></Title>
<URL><![CDATA[https://xxxxx/staging/index.php?p=product&id=80]]></URL>
<ThumbnailImageUrl><![CDATA[http://www.xxxxxxxxxx.com/staging/images/products/thumbs/100040.jpg]]></ThumbnailImageUrl>
<ImageUrl><![CDATA[http://www.xxxxxxxx.com/staging/images/products/100040.jpg]]></ImageUrl>
<Discontinued><![CDATA[No]]></Discontinued>
<Options> </Options>
<Added><![CDATA[2010-05-12 13:50:00]]></Added>
<ManufaturerName><![CDATA[]]></ManufaturerName>
<Description><![CDATA[<p> </p><p> </p>]]></Description>
<AmazonId><![CDATA[]]></AmazonId>
<AmazonItemCondition><![CDATA[]]></AmazonItemCondition>
<AmazonIdType><![CDATA[]]></AmazonIdType>
<EbayCategoryId><![CDATA[]]></EbayCategoryId>
<YahooPath><![CDATA[]]></YahooPath>
<GoogleItemCondition><![CDATA[]]></GoogleItemCondition>
<PricegrabberCategory><![CDATA[]]></PricegrabberCategory>
<PricegrabberItemCondition><![CDATA[]]></PricegrabberItemCondition>
<PricegrabberPartNumber><![CDATA[]]></PricegrabberPartNumber>
<InventoryControl><![CDATA[Yes]]></InventoryControl>
<PID><![CDATA[80]]></PID>
<ProductId><![CDATA[100040]]></ProductId>
<Qoh><![CDATA[1]]></Qoh>
<NextagCategory><![CDATA[]]></NextagCategory>
<NextagPartNumber><![CDATA[]]></NextagPartNumber>
<NextagItemCondition><![CDATA[]]></NextagItemCondition>
</Product>
My code
<?php
$shop='www.xxx.com/staging/content/admin/plugins/openapi/index.php?';
$user = "asd";
$password = "ad";
$token = 'token';
// Assemble the account url
$url = 'https://'.$shop."username=".$user."&password=".$password."&token=".$token. "&apiType=xml&call=GetProducts&mode=hot";
// Setup the cURL object
$curl = curl_init();
curl_setopt($l_oCurl, CURLOPT_POST, 1);
curl_setopt( $curl, CURLOPT_URL, $url );
$response=curl_exec($curl);
curl_close($curl);
$image_xml = new SimpleXMLElement($response);
**foreach($xml->ThumbnailImageUrl as $thumbs){
echo "<img src=".$thumbs."/>";**
}
?>
SimpleXml can load remote URLs with simplexml_load_file and all libxml bases extensions can be used with a custom Stream Context. Just create your custom context with stream_context_create and then set it with libxml_set_streams_context. See Context List and Options
To generate a URL encoded string, use http_build_query
As for using SimpleXml, please see the Basic Usage Examples in the PHP Manual. You basically just have to traverse to the node and echo it, e.g.
echo $sxe->someNode->someOtherNode->ThumbnailImageUrl;

Categories