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
Related
I've been trying unsuccessfully with PHP to loop through two XML files and print the result to the screen. The aim is to take a country's name and output its regions/states/provinces as the case may be.
The first block of code successfully prints all the countries but the loop through both files gives me a blank screen.
The countries file is in the format:
<row>
<id>6</id>
<name>Andorra</name>
<iso2>AD</iso2>
<phone_code>376</phone_code>
</row>
And the states.xml:
<row>
<id>488</id>
<name>Andorra la Vella</name>
<country_id>6</country_id>
<country_code>AD</country_code>
<state_code>07</state_code>
</row>
so that country_id = id.
This gives a perfect list of countries:
$xml = simplexml_load_file("countries.xml");
$xml1 = simplexml_load_file("states.xml");
foreach($xml->children() as $key => $children) {
print((string)$children->name); echo "<br>";
}
This gives me a blank screen except for the HTML stuff on the page:
$xml = simplexml_load_file("countries.xml");
$xml1 = simplexml_load_file("states.xml");
$s = "Jamaica";
foreach($xml->children() as $child) {
foreach($xml1->children() as $child2){
if ($child->id == $child2->country_id && $child->name == $s) {
print((string)$child2->name);
echo "<br>";
}
}
}
Where have I gone wrong?
Thanks.
I suspect your problem is not casting the name to a string before doing your comparison. But why are you starting the second loop before checking if it's needed? You're looping through every single item in states.xml needlessly.
$countries = simplexml_load_file("countries.xml");
$states = simplexml_load_file("states.xml");
$search = "Jamaica";
foreach($countries->children() as $country) {
if ((string)$country->name !== $search) {
continue;
}
foreach($states->children() as $state) {
if ((string)$country->id === (string)$state->country_id) {
echo (string)$state->name . "<br/>";
}
}
}
Also, note that naming your variables in a descriptive manner makes it much easier to figure out what's going on with code.
You could probably get rid of the loops altogether using an XPath query to match the sibling value. I don't use SimpleXML, but here's what it would look like with DomDocument:
$search = "Jamaica";
$countries = new DomDocument();
$countries->load("countries.xml");
$xpath = new DomXPath($countries);
$country = $xpath->query("//row[name/text() = '$search']/id/text()");
$country_id = $country[0]->nodeValue;
$states = new DomDocument();
$states->load("states.xml");
$xpath = new DomXPath($states);
$states = $xpath->query("//row[country_id/text() = '$country_id']/name/text()");
foreach ($states as $state) {
echo $state->nodeValue . "<br/>";
}
I have such php code:
$xml = #simplexml_load_file('2.xml', 'SimpleXMLElement',LIBXML_NOCDATA);
print_r($xml);
How to get values of:
DialingNumber,StartTime,AnswerTime ?
foreach ($xml as $show)
{
echo (string)$show['DialedNumber'];
echo (string)$show['AnswerNumber'];
echo (string)$show['WaitDuration'];
}
NOT WORKING ! How to get values of: DialingNumber,StartTime,AnswerTime ?
There are problems with the the XML file itself, which can be 'corrected' with just replacing some of the entities with some dummy data. The second part is to reference the correct path to the data you want to output.
$filename = '2.xml';
$data = file_get_contents($filename);
$data = str_replace(["&rs", "&rc"], "", $data); // Remove entity references
$xml = simplexml_load_string($data);
foreach ($xml->Tablix1->DialedNumber_Collection->DialedNumber->Details_Collection->Details
as $details)
{
echo (string)$details['DialedNumbers'].PHP_EOL;
echo (string)$details['AnswerNumber'].PHP_EOL;
echo (string)$details['WaitDuration'].PHP_EOL;
}
Can you try as below?
foreach ($xml as $show)
{
echo (string)$show[0]['DialedNumber'];
echo (string)$show[0]['AnswerNumber'];
echo (string)$show[0]['WaitDuration'];
}
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..
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;
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