Here is the XML I am parsing:
https://seekingalpha.com/api/sa/combined/AAPL.xml
When I grab and parse the XML with simplexml_load_file($url) and then do a var_dump on that, it shows that the only children of every "item" are "title", "link", "guid", and "pubDate."
I am trying to access the node "sa:author_name." Why isn't it a child of "item"? Maybe I am misunderstanding something about how XML files are structured. Help me my children are missing lol
To get the data in sa:author_name you have to use the namespace https://seekingalpha.com/api/1.0.
You can for example use a foreach and loop the children using the namespace.
$url = "https://seekingalpha.com/api/sa/combined/AAPL.xml";
$xml = simplexml_load_file($url);
foreach ($xml->channel->item as $item) {
foreach ($item->children("https://seekingalpha.com/api/1.0") as $child) {
if ($child->getName() === "author_name") {
echo $child . "<br>";
}
}
}
Another way you could do it is using an xpath expression:
$authorNames = $xml->xpath('/rss/channel/item/sa:author_name');
foreach ($authorNames as $authorName) {
echo $authorName . "<br>";
}
Which will result in:
Yoel Minkoff
DoctoRx
SA Transcripts
Bill Maurer
etc..
Related
I have following xml getting loaded in my PHP code;
<SiteAlarmDetails>
<AlertId>89637</AlertId>
<SiteCode>20157498</SiteCode>
<SiteName>newport</SiteName>
</SiteAlarmDetails>
$alertXml = simplexml_load_string( $tableAlarm->AlarmDetails);
echo (string) $alertXml->AlertId; //prints **89637**
Now I try to traverse this XML nodes;
foreach($alertXml->children() as $alerts)
{
$alertId = (string)$alerts->AlertId;
echo $alertId;//I do not see anything
}
Is above right approach to traverse AlertId in the foreach loop?
Trying simple foreach will be helpful. Just for accessing single value (eg AlertId) you can use $alertXml->AlertId;.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$xmlString=<<<XML
<SiteAlarmDetails>
<AlertId>89637</AlertId>
<SiteCode>20157498</SiteCode>
<SiteName>newport</SiteName>
</SiteAlarmDetails>
XML;
$alertXml = simplexml_load_string( $xmlString);
foreach($alertXml as $key => $child)
{
echo $key ."=".(string)$alertXml->{$key};
echo PHP_EOL;
}
Output:
AlertId=89637
SiteCode=20157498
SiteName=newport
I wrote a php code for retrieving some data from a XML file into a variable.
This is the XML file:
<Server>
<Server1>
<ipaddress>10.3.2.0</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.1</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.2</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
<Server1>
<ipaddress>10.3.2.3</ipaddress>
<rootpassword>abcd</rootpassword>
<port>22</port>
<autousername>abcd</autousername>
<autopassword>abcd</autopassword>
</Server1>
</Server>
This is the PHP code:
$x = $xmlDoc->getElementsByTagName("ipaddress");
Here i want to display the content of $x by index value, something like
echo $x[0]->nodeValue;
How could I do that?
I assume you used DOMDocument for the XML parsing. When invoking getElementsByTagName you will receive a DOMNodeList not an array.
DOMNodeList implements Traversable so it can be used in foreach loops.
foreach ($x as $item) {
var_dump($item->nodeValue);
}
If you just want a specific item use the item method.
$x->item(0)->nodeValue;
You can access ipaddress like below.
$xml = simplexml_load_file("yourxml.xml");
$result = $xml->xpath('//Server1');
foreach($result as $item){
echo "IP Address:".$item->ipaddress
echo "<br/>";
}
The demo.
$xml = simplexml_load_file($path_to_your_xml_file);
foreach($xml->Server1 as $server) {
echo $server->ipaddress . '<br>';
}
Or you could just do:
echo $xml->Server1[0]->ipaddress;
I'm looking for filtering this xml enter link description here
The best way to filter an xml it is :
-to run all the xml and to affect value in variable
-after that we rewrite this xml with this variable
is there any other method?
For this method i've used the dom like this:
$flux= new DOMDocument();
if ($flux->load('http://xml.weather.com/weather/local/FRXX0076?unit=m&hbhf=6&ut=C'))
{$loc=$flux->getElementsByTagName('t');
foreach($loc as $lo)
echo $lo->firstChild->nodeValue . "<br />";
}
in this code i've tried to display <t> but there are 2 balise <t> in <hour> , therefore i've two value of <t> instead the first child of <hour>
The brief answer:
$flux= new DOMDocument();
if ($flux->load('http://xml.weather.com/weather/local/FRXX0076?unit=m&hbhf=6&ut=C'))
{
$xpath = new DomXPath($flux);
$elements = $xpath->query("*/hour/t[1]");
if (!is_null($elements)) {
foreach ($elements as $element)
{
echo "<br/>[". $element->nodeName. "]";
$nodes = $element->childNodes;
foreach ($nodes as $node)
{
echo $node->nodeValue. "\n";
}
}
}
}
I think you should know where to go from this point :)
More advanced version will be to issue XPath query on all hour elements ("*/hour") and then in foreach for each hour element issue another xpath query in this element context ($xpath->query("*/t[1]", $hourElement);). This way you'll also have access to hour object and can for example display this hour.
UPDATE
Simpler version of foreach:
if (!is_null($elements)) {
foreach ($elements as $element)
{
echo "<br/>".$element->nodeValue;
}
}
probably a simple question to answer for someone:::
xml:
<foobar>
<foo>i am a foo</foo>
<bar>i am a bar</bar>
<foo>i am a <bar>bar</bar></foo>
</foobar>
In the above, I want to display all elements that are <foo>. When the script gets to the line with the nested < bar > the result is "i am a bar" .. which isn't the result I had hoped for.
Is it not possible to print out the entire contents of that element as it is, so that i see: "i am a <bar>bar</bar>"
php:
$xml = file_get_contents('sample');
$dom = new DOMDocument;
#$dom->loadHTML($xml);
$resources= $dom->getElementsByTagName('foo');
foreach ($resources as $resource){
echo $resource->nodeValue . "\n";
}
After some trolling and trying to do what I needed with SimpleXML, I arrived at the following conclusion. My issue with SimpleXML was where the elements are. If the xml is structured, and the hierarchy is standard ... I have no problem.
If the XML is a web page for example, and the <foo> element is anywhere, SimpleXML doesn't have a good facility like getElementsByTagName to pull out the element wherever it may be....
<?php
$doc = new DOMDocument();
$doc->load('sample');
$element_name = 'foo';
if ($doc->getElementsByTagName($element_name)->length > 0) {
$resources = $doc->getElementsByTagName($element_name);
foreach ($resources as $resource) {
$id = null;
if (!$resource->hasAttribute('id')) {
$resource->setAttribute('id', gen_uuid());
}
$innerHTML = null;
$children = $resource->childNodes;
foreach ($children as $child) {
$tmp_doc = new DOMDocument();
$tmp_doc->appendChild($tmp_doc->importNode($child,true));
$innerHTML .= rtrim($tmp_doc->saveHTML());
}
$resource->nodevalue = $innerHTML;
}
}
echo $doc->saveHTML();
?>
Rather than writing all that code, you might try XPath. That expression would be "//foo", which would get a list of all the elements in the document named "foo".
http://php.net/manual/en/simplexmlelement.xpath.php
I'm learning how to parse XML with PHP's simple XML. My code is:
<?php
$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\"> <iTunes> myApp </iTunes> </Document>";
$xml = new SimpleXMLElement($xmlSource);
$results = $xml->xpath("/Document/iTunes");
foreach ($results as $result){
echo $result.PHP_EOL;
}
print_r($result);
?>
When this runs it returns a blank screen, with no errors. If I remove all the attributes from the Document tag, it returns :
myApp SimpleXMLElement Object ( [0] => myApp )
Which is the expected result.
What am I doing wrong? Note that I don't have control over the XML source, since it's coming from Apple.
Your xml contains a default namespace. In order to get your xpath query to work you need to register this namespace, and use the namespace prefix on every xpath element you are querying (as long as these elements all fall under the same namespace, which they do in your example):
$xml = new SimpleXMLElement( $xmlSource );
// register the namespace with some prefix, in this case 'a'
$xml->registerXPathNamespace( 'a', 'http://www.apple.com/itms/' );
// then use this prefix 'a:' for every node you are querying
$results = $xml->xpath( '/a:Document/a:iTunes' );
foreach( $results as $result )
{
echo $result . PHP_EOL;
}
For the part about the default namespace, read fireeyedboy's answer. As mentionned, you need to register a namespace if you want to use XPath on nodes that are in the default namespace.
However, if you don't use xpath(), SimpleXML has its own magic that selects the default namespace automagically.
$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\"> <iTunes> myApp </iTunes> </Document>";
$Document = new SimpleXMLElement($xmlSource);
foreach ($Document->iTunes as $iTunes)
{
echo $iTunes, PHP_EOL;
}
this is general example
foreach ($library->children() as $child)
{
echo $child->getName() . ":\n";
foreach ($child->attributes() as $attr)
{
echo $attr->getName() . ': ' . $attr . "\n";
}
foreach ($child->children() as $subchild)
{
echo $subchild->getName() . ': ' . $subchild . "\n";
}
echo "\n";
}
for more information check this :
http://www.yasha.co/XML/how-to-parse-xml-with-php-simplexml-DOM-Xpath/article-1.html
This line:
print_r($result);
is outside the foreach loop. Maybe you should try
print_r($results);
instead.
Seems if you use the wildcard (//) on xpath it will work. Also, not sure why but if you remove the namespace attribute (xmlns) from the Document element, your current code will work. Maybe because a prefix isn't defined? Anyway, following should work:
$results = $xml->xpath("//iTunes");
foreach ($results as $result){
echo $result.PHP_EOL;
}