Parse XML namespaces with php SimpleXML
I have given same type of answer here - solution to your question
You just need to register Namespace and then you can work normally with simplexml_load_file and XPath
<?php
$data = "http://alerts.weather.gov/cap/tx.php?x=1";
$entries = file_get_contents($data);
$entries = new SimpleXmlElement($entries);
if(count($entries)):
//echo "<pre>";print_r($entries);die;
//alternate way other than registring NameSpace
//$asin = $asins->xpath("//*[local-name() = 'ASIN']");
$entries->registerXPathNamespace('prefix', 'http://www.w3.org/2005/Atom');
$result = $entries->xpath("//prefix:entry");
//echo count($asin);
//echo "<pre>";print_r($result);die;
foreach ($result as $entry):
//echo "<pre>";print_r($entry);die;
$dc = $entry->children('urn:oasis:names:tc:emergency:cap:1.1');
echo $dc->event."<br/>";
echo $dc->effective."<br/>";
echo "<hr>";
endforeach;
endif;
That's it.
parse an XML with SimpleXML which has multiple namespaces
I think you need to register the namespacing and access with XPath. Something like the following should get you going (I haven't the facility to test this).
$xml = simplexml_load_string($res, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('soap-env', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('eb', 'http://www.ebxml.org/namespaces/messageHeader');
$xml->registerXPathNamespace('wsse', 'http://schemas.xmlsoap.org/ws/2002/12/secext');
Then you can do something like:
foreach($xml->xpath('//eb:MessageHeader') as $header)
{
var_export($header->xpath('//eb:CPAId')); // Should output 'something'.
}
You may not need to register the namespacing, thinking about it, as they are alredy present in the XML. Not sure on this though, would need to test.
Hope this helps.
Parse xml with namespaces with SimpleXMLparser php
You should not read the namespaces from the document. The namespace is a unique string defining the XML semantic the tag is part of. Your XML is a good example for that, because it has Point
elements in two different namespaces.
p:Point
is {http://example.org}:Pointgml:Point
is {http://www.opengis.net/gml}:Point
The namespace prefixes like p
and gml
are aliases to make a document smaller and more readable. They are only valid for the element and its children. They can be redefined at any point. More important they are only valid for the document.
So to read XML you define own prefixes for the namespaces and use them with Xpath or you use the namespace aware variants of the DOM methods like getAttributeNS()
. Xpath is by a long way the more elegant solution. You can use the prefixes from the document or different ones.
$element = simplexml_load_string($content);
$element->registerXPathNamespace('gml', 'http://www.opengis.net/gml');
$element->registerXPathNamespace('p', 'http://example.org');
$result = [];
$positions = $element->xpath('//p:Point[1]//gml:pos');
foreach ($positions as $pos) {
$result[] = (string)$pos;
}
var_dump($result);
Output: https://eval.in/159739
array(5) {
[0]=>
string(23) "-3.84307585 43.46031547"
[1]=>
string(23) "-3.84299411 43.46018513"
[2]=>
string(23) "-3.84299935 43.45998723"
[3]=>
string(23) "-3.84309913 43.46054546"
[4]=>
string(23) "-3.84307585 43.46031547"
}
How to easily parse XML documents with namespaces in PHP using SimpleXML?
Got my answer from the code provided by IMSoP. The PHP snippet I ended up using was adapted from aforementioned link, using XML similar to that of the OP:
foreach ($xml->children(NS_ATOM)->entry as $entry) {
echo "<item>".PHP_EOL;
echo "<title>".$entry->title."</title>".PHP_EOL;
echo "<link>".$entry->link->attributes(null)->href."</link>".PHP_EOL;
echo "<image>".$entry->children(NS_MEDIA)->group->children(NS_MEDIA)->thumbnail->attributes(null)->url."</image>".PHP_EOL;
echo "<description>".$entry->children(NS_MEDIA)->group->children(NS_MEDIA)->description."</description>".PHP_EOL;
echo "<guid>".$entry->children(NS_YT)->videoId."</guid>".PHP_EOL;
echo "<views>".$entry->children(NS_MEDIA)->group->children(NS_MEDIA)->community->children(NS_MEDIA)->statistics->attributes(null)->views."</views>".PHP_EOL;
echo "<pubDate>".$entry->published."</pubDate>".PHP_EOL;
echo "</item>".PHP_EOL;
}
Hope this can help somebody in the future. It was the easiest example of XML namespace parsing I've come across so far.
Parse XML namespace and schema in PHP
There are quite a few problems with the method your trying, this method uses XPath to find the data your after and this removes a lot of the need to move around the DOM to find data. The main thing with XPath though is to register the namespaces to allow you to use them in the query...
$myFileXml = 'feds200628.xml';
$xml = simplexml_load_file($myFileXml);
$xml->registerXPathNamespace('frb', 'http://www.federalreserve.gov/structure/compact/common');
$xml->registerXPathNamespace('kf', "http://www.federalreserve.gov/structure/compact/Yields_Parameters");
$ns_dc = $xml->xpath("//frb:DataSet[2]/kf:Series[1]/frb:Obs");
echo $ns_dc[0]->Attributes()->OBS_VALUE.PHP_EOL;
$count = count($ns_dc);
echo $count.PHP_EOL;
The XPath returns just the Obs elements (Note that XPath arrays are 1 based whereas PHP arrays are 0 based - which is why I use 2 to fetch the second element).
How do I parse XML containing custom namespaces using SimpleXML?
the usage of ccc:fid is an extension of the namespace which needs to be declared in xml in order to be able to use it in libraries like simplexml.
Here are some examples of descriptions of usin a namespace:
- http://www.w3.org/TR/1999/REC-xml-names-19990114/
- http://www.w3.org/TR/xml-names/
Hope that helps, albeit it is a little complicated.
Parse XML namespace format in PHP
Thanks to @IMSoP, I got the solution:
$xml = simplexml_load_string($xmlstring);
$rows = $xml->Row->APIReportRow;
foreach ($rows as $row) {
$cell = $row->Cell->children('d4p1', true);
echo "Name: " . (string) $cell->string[0] . "\n";
echo "Surname: " . (string) $cell->string[1] . "\n";
}
XML - getting value from namespace using SimpleXML
The children()
method doesn't return some kind of token for the namespace, it returns a list of elements - the children which are in the given namespace.
The $xml
variable represents the top-level message
element, which doesn't have any children in the http://www.blendlabs.com
namespace, so $xml->children('http://www.blendlabs.com')
will just return an empty list. You need to first navigate to the other
element, and then get its children in the http://www.blendlabs.com
namespace, which will include the loan
element.
Since the top level element is in the http://www.mismo.org/residential/2009/schemas
namespace, you might need an extra children() call to make sure you select that first.
You didn't provide a complete XML, so I can't test the code (I don't fancy manually writing all those close tags), but it will look something like this:
$marketing_value = (string)
$xml
->children('http://www.mismo.org/residential/2009/schemas')
->deal_sets->deal_set->deals->deal->loans->loan->extension->other
->children('http://www.blendlabs.com')
->loan->marketing_items->marketing_item->marketingvalue;
Related Topics
How to Generate Random Date Between Two Dates Using PHP
How to Use Cookies Across Two Different Domains
Object of Class Datetime Could Not Be Converted to String
How to Sum N Number of Time (Hh:Mm Format)
Php-Fpm Doesn't Write to Error Log
Correct Way to Set Bearer Token with Curl
Using PHP Replace Spaces in Urls with %20
Force Browser to Download Image with JavaScript Window.Open
How to Call a Model from a View
Generating Xml Document in PHP (Escape Characters)
PHP - Regex to Allow Letters and Numbers Only
PHP Exec $Path Variable Missing Elements
How to Use Mamp's Version of PHP Instead of the Default on Osx
Handling Expired Token in Laravel
How to Set .Env Values in Laravel Programmatically on the Fly