So i have these simplexmlelement objects. And i cant get it to work how to parse a specific element.
SimpleXMLElement Object
(
[Generation] => SimpleXMLElement Object
(
[#attributes] => Array
(
[version] => 3.1.0-alpha3
[timestamp] => 1355434832
)
)
[Options] => SimpleXMLElement Object
(
[#attributes] => Array
(
[tempFormat] => c
[byteFormat] => auto_binary
[refresh] => 60000
[showPickListTemplate] => true
[showPickListLang] => true
)
)
[UsedPlugins] => SimpleXMLElement Object
(
)
[Vitals] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Hostname] => domain.tld
[IPAddr] => 127.0.0.1
[Kernel] => 2.6.32-11-pve (SMP) x86_64
[Distro] => Ubuntu 12.04.1 LTS
[Distroicon] => Ubuntu.png
[Uptime] => 1993669.51
[Users] => 1
[LoadAvg] => 0.08 0.02 0.01
[CPULoad] => 0
)
)
....etc...
)
I have made something like this to access the Hostname for example:
echo $xml->Generation->Vitals[0]->Hostname;
But i think i am doing something wrong. Could someone point me in the right direction?
It would just be:
$xml->Vitals[0]->attributes()->Hostname
I am not entirely sure if you have to stick with a SimpleXml object, but if you don't, have a look at the DOMDocument and DOMXPath combination. I really like it. Just to be clear, it's hard to get into, but as soon as you get the hang of it, you are going to like it.
You can just do something like this:
$doc = new DOMDocument();
$doc->load('http://www.example.com/file.xml');
$xpath = new DOMXPath($doc);
$result = $xpath->query('//Vitals');
// print them all
foreach ($result as $r){
echo $r->getAttribute('Hostname'); //your desired value
}
// or just the first one
echo $result->item(0)->getAttribute('Hostname');
You could also make the query slightly bigger to get the attribute right away like so: //Vitals#Hostname which should work as well.
And with this start you will possibly get the hang of it.
Further reading:
http://php.net/manual/en/class.domdocument.php
http://php.net/manual/en/class.domxpath.php
http://php.net/manual/en/domxpath.query.php
http://www.tizag.com/xmlTutorial/xpathattribute.php
http://www.w3schools.com/xpath/xpath_syntax.asp
Related
I'm using the namecheap API to do some stuff, it's the first time I've used a API and I'm running into a bit of a problem.
This is what I have so far:
$ApiKey = "**********************";
$ApiUser = "*****";
$UserName = "*********";
$ClientIP = "********";
$NamecheapURI = "https://api.namecheap.com/xml.response";
$executionURL = $NamecheapURI."?ApiUser=".$ApiUser."&ApiKey=".$ApiKey."&UserName=".$UserName."&Command=namecheap.domains.check&ClientIp=".$ClientIP."&DomainList=".$domain;
$xml = simplexml_load_file($executionURL);
print_r($xml);
When print $xml I am returned simple XML objects:
SimpleXMLElement Object
(
[#attributes] => Array
(
[Status] => OK
)
[Errors] => SimpleXMLElement Object
(
)
[Warnings] => SimpleXMLElement Object
(
)
[RequestedCommand] => namecheap.domains.check
[CommandResponse] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Type] => namecheap.domains.check
)
[DomainCheckResult] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Domain] => facebook.com
[Available] => false
[ErrorNo] => 0
[Description] =>
[IsPremiumName] => false
[PremiumRegistrationPrice] => 0
[PremiumRenewalPrice] => 0
[PremiumRestorePrice] => 0
[PremiumTransferPrice] => 0
[IcannFee] => 0
[EapFee] => 0
)
)
)
[Server] => PHX01APIEXT03
[GMTTimeDifference] => --5:00
[ExecutionTime] => 0.008
)
My question is beyond this, how do I move forward and pull data from this?
I've tried treating this as an array but I am getting nowhere, when using is_array() to test if it was an array it says it's not which I don't understand...
I apologise if this is a noob question, I am a bit new to this. In short, what do I need to do to pull data from this?
Thanks in advance!
Learning to use SimpleXML is much better than trying to convert it to arrays/json/anything else and simple (hence the name). A quick example...
$response = '<?xml version="1.0" encoding="UTF-8"?>
<CommandResponse Type="namecheap.domains.check">
<DomainCheckResult Domain="facebook.com">
<Element>1234</Element>
<Element>12345</Element>
</DomainCheckResult>
</CommandResponse>';
$xml = simplexml_load_string($response);
echo "DOmain=".$xml->DomainCheckResult['Domain'].PHP_EOL;
foreach ( $xml->DomainCheckResult->Element as $value) {
echo "Value=".(string)$value.PHP_EOL;
}
outputs...
DOmain=facebook.com
Value=1234
Value=12345
You have to adapt this to your own XML, but the idea is that if you want to access an element of an item you use object notation -> and if you need to get an attribute, use array notation [].
So in the above code, the first echo ($xml->DomainCheckResult['Domain']) gets the <DomainCheckResult> element and outputs the Domain attribute.
Then the foreach loop says fetch each <Element> within <DomainCheckResult> and output the value.
I have a SimpleXMLElement object that I got from parsing a response from oData. I'm looping through the children and it works well as long as it has children (the truth is I'm not even sure if they are its children or if its just a collection). This is how my code looks like:
$dataset = soapService->doSoapCall();
$array = $dataset->children()->children();
foreach($rawArray as $element)
{
$row['Something'] = (string)$element->Something;
$newArr[] = $row;
}
The problem is that this code throws an error of: PHP Node no longer exists SimpleXML. I've been trying to check for null or check the count of it but I keep getting the same error. When I look at it from the debugger in net beans it just says its type SimpleXMLElement but I doesn't have any other value or children. Please help.
Note: When I do print_r($array) i get this:
SimpleXMLElement Object ( )
When the object actually has data it returns this:
SimpleXMLElement Object ( [Table] => Array ( [0] => SimpleXMLElement Object ( [EventCode] => 10020 ) [1] => SimpleXMLElement Object ( [EventCode] => 10030 ) [2] => SimpleXMLElement Object ( [EventCode] => 10040 ) ) ) {"code":99200}
i wont to list a set of files in a directory and the files in its sub directory using a loop rather than the function
as im getting the information about the directory through an xml based webdav and php native functions are infertile so please understand the issue has not yet been lodged here
$urlloc is used to remove the same directory from being looped again
foreach ($xml as $key) {
if(empty($key->propstat->prop->resourcetype[0])){
echo $key->href."<br/>";//files are printed, for debugging perposes im printing it
}else{
$Nurlloc=$key->href;
if ($Nurlloc!=$urlloc){
echo "<b>".$Nurlloc."</b><br/>";//directorys printed in bold for debugging
$urlloc=$Nurlloc;
//gtndirdown()
above is the method im getting to know if its a directory or not
NOTE i want to be able to make this code loop through and get me all the files in the directory i will also post the array of files im getting
[response] => Array
(
[0] => SimpleXMLElement Object
(
[href] => /dav/product_images/
[propstat] => SimpleXMLElement Object
(
[prop] => SimpleXMLElement Object
(
[resourcetype] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[quota-used-bytes] => 2147483647
[quota-available-bytes] => 2147483647
)
[status] => HTTP/1.1 200 OK
)
)
[1] => SimpleXMLElement Object
(
[href] => /dav/product_images/a/
[propstat] => SimpleXMLElement Object
(
[prop] => SimpleXMLElement Object
(
[resourcetype] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[quota-used-bytes] => 2147483647
[quota-available-bytes] => 2147483647
)
[status] => HTTP/1.1 200 OK
)
)
iv been stuck in this issue for 4 days and i have would like if some one could come up with a logic for this issue
maybe this is an idea that you can implement in your logic
// the name of directory
$dir='path_to_your_directory';
$files = array_slice(scandir($dir), 2);
print_r($files);
As I have mentioned in question title, I am trying below code to reach till the desired node in xpath result.
<?php
$xpath = '//*[#id="topsection"]/div[3]/div[2]/div[1]/div/div[1]';
$html = new DOMDocument();
#$html->loadHTMLFile('http://www.flipkart.com/samsung-galaxy-ace-s5830/p/itmdfndpgz4nbuft');
$xml = simplexml_import_dom($html);
if (!$xml) {
echo 'Error while parsing the document';
exit;
}
$source = $xml->xpath($xpath);
echo "<pre>";
print_r($source);
?>
this is the source code. I am using to scrap price from a ecommerce.
it works it gives below output :
Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[class] => line
)
[div] => SimpleXMLElement Object
(
[#attributes] => Array
(
[class] => prices
[itemprop] => offers
[itemscope] =>
[itemtype] => http://schema.org/Offer
)
[span] => Rs. 10300
[div] => (Prices inclusive of taxes)
[meta] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[itemprop] => price
[content] => Rs. 10300
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[itemprop] => priceCurrency
[content] => INR
)
)
)
)
)
)
Now How to reach till directly [content] => Rs. 10300.
I tried:
echo $source[0]['div']['meta']['#attributes']['content']
but it doesn't work.
Try echo (String) $source[0]->div->meta[0]['content'];.
Basically, when you see an element is an object, you can't access it like an array, you need to use object -> approach.
The print_r of a SimpleXMLElement does not show the real object structure. So you need to have some knowledge:
$source[0]->div->meta['content']
| | | `- attribute acccess
| | `- element access, defaults to the first one
| `- element access, defaults to the first one
|
standard array access to get
the first SimpleXMLElement of xpath()
operation
That example then is (with your address) the following (print_r again, Demo):
SimpleXMLElement Object
(
[0] => Rs. 10300
)
Cast it to string in case you want the text-value:
$rs = (string) $source[0]->div->meta['content'];
However you can already directly access that node with the xpath expression (if that is a single case).
Learn more on how to access a SimpleXMLElement in the Basic SimpleXML usage ExamplesDocs.
I am going crazy here...
I already have a SimpleXMLElement Object so it is not an XML file...
I got it stored in a file object.txt
Now i want to put this object into a variable, but i can't get it to work...?
the SimpleXMLElement Object looks like this:
SimpleXMLElement Object
(
[PubmedArticle] => Array
(
[0] => SimpleXMLElement Object
(
[MedlineCitation] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Owner] => NLM
[Status] => In-Process
)
[PMID] => 20538400
[DateCreated] => SimpleXMLElement Object
(
[Year] => 2010
[Month] => 07
[Day] => 08
)
[Article] => SimpleXMLElement Object
(
[#attributes] => Array
(
[PubModel] => Print-Electronic
)
.....etc etc....
how do i put this into a variable??
i tried this:
$simplexml = file_get_contents('object.xml');
$simplexml should be an array
Loading simplexml from file: simplexml_load_file: $a = simplexml_load_file('object.xml');
If you need something else, please explain.
If your 'object.xml' file contains the above example and not actual XML, it looks a lot like you are using the results of a vardump, and you possibly wish to load that into a (or several) SimpleXMLElementObject(s)...
So, really, you have a string inside of a text file, and you want to parse out the contents. I found this: converting text file into xml using php? and thought it would be a good starting point.