Php xml get all tags

Show XML tag full path with php

Let’s assume we want to process this Feed: http://tools.forestview.eu/xmlp/xml_feed.php?aid=1094&cid=1000 I’m trying to show the nodes of an XML file this way:

deals->deal->dealsite deals->deal->deal_id deals->deal->deal_title 

This is in order to be able to process feeds that we don’t know what their XML tags are. So we will let the user choose that deals->deal->deal_title is the Deal Title and will recognize it that way. I have been trying ages to do this with this code:

 class HandleXML < var $root_tag = false; var $xml_tags = array(); var $keys = array(); function parse_recursive(SimpleXMLElement $element) < $get_name = $element->getName(); $children = $element->children(); // get all children if (empty($this->root_tag)) < $this->root_tag = $this->root_tag.$get_name; > $this->xml_tags[] = $get_name; // only show children if there are any if(count($children)) < foreach($children as $child) < $this->parse_recursive($child); // recursion :) > > else < $key = implode('->', $this->xml_tags); $this->xml_tags = array(); if (!in_array($key, $this->keys)) < if (!strstr('>', $key) && count($this->keys) > 0) < $key = $this->root_tag.'->'.$key; > if (!in_array($key, $this->keys)) < $this->keys[] = $key; > > > > > $xml = new SimpleXMLElement($feed_url, null, true); $handle_xml = new HandleXML; $handle_xml->parse_recursive($xml); foreach($handle_xml->keys as $key) < echo $key.'
'; > exit;
deals->deal->dealsite deals->deal_id deals->deal_title 

Источник

DOMDocument::getElementsByTagName

This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.

Parameters

The local name (without namespace) of the tag to match on. The special value * matches all tags.

Return Values

A new DOMNodeList object containing all the matched elements.

Examples

Example #1 Basic Usage Example

$dom = new DOMDocument ;
$dom -> loadXML ( $xml );
$books = $dom -> getElementsByTagName ( ‘book’ );
foreach ( $books as $book ) echo $book -> nodeValue , PHP_EOL ;
>
?>

Читайте также:  pre

The above example will output:

Patterns of Enterprise Application Architecture Design Patterns: Elements of Reusable Software Design Clean Code

See Also

User Contributed Notes 14 notes

Return if there are no matches is an empty DOMNodeList. Check using length property, e.g.:

$nodes = $domDocument -> getElementsByTagName ( ‘book’ ) ;
if ( $nodes -> length == 0 ) <
// no results
>
?>

Note that when using getElementsByTagName that it is a dynamic list. Thus if you have code which adjusts the DOM structure it will change the results of the getElementsByTagName results list.

The following code iterates through a complete set of results and changes them all to a new tag:

$nodes = $xml -> getElementsByTagName ( «oldtag» );

$nodeListLength = $nodes -> length ; // this value will also change
for ( $i = 0 ; $i < $nodeListLength ; $i ++)
$node = $nodes -> item ( 0 );

// some code to change the tag name from «oldtag» to something else
// e.g. encrypting a tag element
>
?>

Since the list is dynamically updating, $nodes->item(0) is the next «unchanged» tag.

My first post!
And this is how I get elements by attribute and its value.
For an example, if I want to grab all DIV tags with class name ‘className’, then.

$some_link = ‘some website’ ;
$tagName = ‘div’ ;
$attrName = ‘class’ ;
$attrValue = ‘className’ ;

$dom = new DOMDocument ;
$dom -> preserveWhiteSpace = false ;
@ $dom -> loadHTMLFile ( $some_link );

$html = getTags ( $dom , $tagName , $attrName , $attrValue );
echo $html ;

function getTags ( $dom , $tagName , $attrName , $attrValue ) $html = » ;
$domxpath = new DOMXPath ( $dom );
$newDom = new DOMDocument ;
$newDom -> formatOutput = true ;

$filtered = $domxpath -> query ( «// $tagName » . ‘[@’ . $attrName . «=’ $attrValue ‘]» );
// $filtered = $domxpath->query(‘//div[@class=»className»]’);
// ‘//’ when you don’t know ‘absolute’ path

// since above returns DomNodeList Object
// I use following routine to convert it to string(html); copied it from someone’s post in this site. Thank you.
$i = 0 ;
while( $myItem = $filtered -> item ( $i ++) ) $node = $newDom -> importNode ( $myItem , true ); // import node
$newDom -> appendChild ( $node ); // append node
>
$html = $newDom -> saveHTML ();
return $html ;
>

?>

Please, improve it, and share it.

Following Example is of multiple attributes and multiple child nodes. this is being used to make joomla plugin for bulk upload of articles. Gurmukh Singh Bhatti

$dom = new DomDocument ;
$dom -> preserveWhiteSpace = FALSE ;
$dom -> loadXML ( $xml );
$params = $dom -> getElementsByTagName ( ‘section’ ); // Find Sections
$k = 0 ;
foreach ( $params as $param ) //go to each section 1 by 1
echo «Section Attribute :-> » . $params -> item ( $k )-> getAttribute ( ‘name’ ). «
» ; //get section attribute
$params2 = $params -> item ( $k )-> getElementsByTagName ( ‘category’ ); //digg categories with in Section
$i = 0 ; // values is used to iterate categories
foreach ( $params2 as $p ) echo »  — Category Attribute Name :-> » . $params2 -> item ( $i )-> getAttribute ( ‘name’ ). «
» ; //get Category attributes
$params3 = $params2 -> item ( $i )-> getElementsByTagName ( ‘arti’ ); //dig Arti into Categories
$j = 0 ; //values used to interate Arti
foreach ( $params3 as $p2 )
echo »   — Article Attribute Name : » . $params3 -> item ( $j )-> getAttribute ( ‘name’ ). «» ; //get arti atributes
echo »   Value : » . $params3 -> item ( $j )-> nodeValue . «
» ; //get Node value ;
$j ++;
>
$i ++;
>
$k ++;

>
?>

output :
Section Attribute :-> Section1
— Category Attribute Name :-> google
— Article Attribute Name : article1 Value : any html code heremy name is so so
— Article Attribute Name : article2 Value : value2
— Article Attribute Name : article3 Value : value3
— Article Attribute Name : article4 Value : value4
— Category Attribute Name :-> yahoo
— Article Attribute Name : articleSection2 Value : Test value
Section Attribute :-> Section2
— Category Attribute Name :-> msn
— Article Attribute Name : article2 Value : value1
— Article Attribute Name : article3 Value : value2
— Category Attribute Name :-> webcare
— Article Attribute Name : param3 Value : value4

Here is an example of getElementsByTagName():

$dom = new DomDocument ;
$dom -> preserveWhiteSpace = FALSE ;
$dom -> loadXML ( $xml );
$params = $dom -> getElementsByTagName ( ‘param’ );

foreach ( $params as $param ) echo $param -> getAttribute ( ‘name’ ). ‘
‘ ;
>
?>

Expected result:
—————
param1
param2
param3

This is a very simplistic way to traverse xml nodes and childnodes using the DOMDocument class

I was in need of $dom->getElementsByTagName that would hist magic within a contextNode.

Why i needed getElementsByTagName instead of just simple using an xPath->query is because while looping through the returned nodelist, more nodes with the tagName i was looking for where created.

When using getElementsByTagName, the new nodes are «added» to the nodelist i already am looping through.

When using an xpath query, you wil only loop through the original nodelist, the newly created elements wil not appear in that nodelist.

I was already using an extended class on domDocument, so it was simple to create an kind of getElementsByTagName that would accept an contextNode.

class SmartDocument extends DOMDocument private $localDom ;
public $xpath ;
private $serialize = array( ‘localDom’ );

private $elemName ;
private $elemCounter ;

/**
* Constructor
*/
function __construct () parent :: __construct ( ‘1.0’ , ‘UTF-8’ );
$this -> preserveWhiteSpace = false ;
$this -> recover = TRUE ;
$this -> xpath = new DOMXpath ( $this );
>

/**
* GetElementsByTagname within an contextNode
*
* @param string $name
* @param DomNode $contextNode
* @return DOMNode|NULL
*/
public function getElementsByTagNameContext ( $name , $contextNode )

if( $this -> elemName != $name ) $this -> elemCounter = 0 ;
$this -> elemName = $name ;
>

$this -> elemLength = $this -> xpath -> evaluate ( ‘count(.//*[name() keyword»>. $this -> elemName . ‘»])’ , $contextNode );
while( $this -> elemCounter < $this ->elemLength ) $this -> elemCounter ++;
$nl = $this -> xpath -> query ( ‘.//*[name() keyword»>. $this -> elemName . ‘»][‘ . $this -> elemCounter . ‘]’ , $contextNode );
if( $nl -> length == 1 ) return $nl -> item ( 0 );
>
>

$this -> elemLength = null ;
$this -> elemCounter = null ;
$this -> elemName = null ;
return null ;
>
>

$doc = new SmartDocument ();
$doc -> load ( ‘book.xml’ );

$nl = $doc -> query ( ‘//books’ );
foreach( $nl as $node ) while( $book = $doc -> getElementsByTagNameContext ( ‘book’ , $node )) //When you now create new nodes within this loop as child or following-sibling of this node
// They show up within this loop
>

Источник

getting xml data as is(with tags, attributes and values) with php

Hello im struggling with a problem. I have an url that contains xml data. when i’m using file_get_contents($url) or fopen($url,’r’) it gives me only values: Consider the xml:

 some Value some Other Value . . 

what i get: some Value, some Other Value But i need to get whole xml (with tags and attributes and its’ values) and parse it with my own way because there’s a restriction that i’m not allowed to use php 5.x practices.I mean i cant use any parser.. It shouldnt be so hard to get xml data as is.. should it??

2 Answers 2

what i get: some Value, some Other Value

Nope — my suspicion is that that is what you see in your browser, because it is swallowing all .

The XML source code will be there after a file_get_contents() operation.

You are using file_get_contents() which states

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.

Press Ctrl+u to see the source code in any of the major browsers(except IE where its F12 in IE9). I am sure that your code will be there. Your browser wont display the tags that’s all.

The other longer(but better way) to display an XML file from your php file is to pass the content type as text/xml . Use the following way

Источник

Оцените статью