How to extract a node attribute from XML using PHP's DOM Parser
Using simpleXML:
$xml = new SimpleXMLElement($xmlstr);
echo $xml->file['path']."\n";
Output:
http://www.thesite.com/download/eysjkss.zip
Using PHP to Parse XML to get Attribute values?
Is there a particular reason you must use SimpleXML? if none, you could try with DOMDocument instead. Code is below:
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->load('example.xml');
$properties = $dom->getElementsByTagName('property');
foreach($properties AS $property)
{
$value = $property->nodeValue;
$type = $property->getAttribute('type');
echo '<div>Node Information/Value :'. $value. '<br/>'. 'Node attribute:'. $type. '</div>';
}
Extract Tag Attribute Content From XML
Using DOMDocument class you can make PHP read the XML and then look for the tag elements in it
http://php.net/DOMDocument
Example
$document = new DOMDocument();
$document->loadXML($xml);
$tags = $document->getElementsByTagName("www");
...
Extract a node value from a xml file and update that value with php
I think you've got two small errors in your code. In the XPATH
$nodes = $xpath->query("//item[IID='$IId']/IqtyOH");
The IID
element should be IId
. So you get:
$nodes = $xpath->query("//item[IId='$IId']/IqtyOH");
Secondly $node
is the value of the node you found, not a reference to it, so you can't call nodeValue
on it. Instead you can do this:
$node = $nodes->item(0)->nodeValue;
$node++;
$nodes->item(0)->nodeValue =$node;
How to get the value of an attribute from XML file in PHP?
You should be able to get this using SimpleXMLElement::attributes()
Try this:
$xml=simplexml_load_file($file);
foreach($xml->Var[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
That will show you all the name/value attributes for the first foo
element. It's an associative array, so you can do this as well:
$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];
How do I remove a specific node using its attribute value in PHP XML Dom?
Ok, let’s try this complete example of use:
function CatRemove($myXML, $id) {
$xmlDoc = new DOMDocument();
$xmlDoc->load($myXML);
$xpath = new DOMXpath($xmlDoc);
$nodeList = $xpath->query('//category[@id="'.(int)$id.'"]');
if ($nodeList->length) {
$node = $nodeList->item(0);
$node->parentNode->removeChild($node);
}
$xmlDoc->save($myXML);
}
// test data
$xml = <<<XML
<?xml version="1.0"?>
<details>
<person>name</person>
<data1>some data</data1>
<data2>some data</data2>
<data3>some data</data3>
<category id="0">
<categoryName>Cat 1</categoryName>
<categorydata1>some data</categorydata1>
</category>
<category id="1">
<categoryName>Cat 2</categoryName>
<categorydata1>some data</categorydata1>
<categorydata2>some data</categorydata2>
<categorydata3>some data</categorydata3>
<categorydata4>some data</categorydata4>
</category>
</details>
XML;
// write test data into file
file_put_contents('untitled.xml', $xml);
// remove category node with the id=1
CatRemove('untitled.xml', 1);
// dump file content
echo '<pre>', htmlspecialchars(file_get_contents('untitled.xml')), '</pre>';
PHP Xpath extracting a value for a node with attribute name= author
Here is the solution. Basically you can make an XPath call off the result node to get all attribute elements with the name attribute equal to author.
Then you check and make sure a result came back, and if it did, it will be index[0] since XPath calls return an array of results. Then you use the attributes()
function to get an associate array of the attribute, finally getting the value you want.
$XML = simplexml_load_string($xml_string);
$XMLResults = $XML->xpath('/GSP/RES/R');
foreach($XMLResults as $Result) {
$Label = $Result->Label;
$AuthorAttribute = $Result->xpath('//Attribute[@name="author"]');
// Make sure there's an author attribute
if($AuthorAttribute) {
// because we have a list of elements even if there's one result
$attributes = $AuthorAttribute[0]->attributes();
$Author = $attributes['value'];
}
else {
// No Author
}
}
How to extract all values of a node in xml using xml parser in C#?
Using Xml Linq you can flatten results to on class object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication152
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<FBTType> fBTTypes = doc.Descendants("FBType").Select(x => new FBTType()
{
guid = (string)x.Attribute("GUID"),
typeName = (string)x.Attribute("Name"),
comment = (string)x.Attribute("Comment"),
ns = (string)x.Attribute("Namespace"),
name = (string)x.Element("Attribute").Attribute("Name"),
value = (string)x.Element("Attribute").Attribute("Value"),
identification = (string)x.Element("Identification").Attribute("Standard"),
organization = (string)x.Element("VersionInfo").Attribute("Organization"),
version = (string)x.Element("VersionInfo").Attribute("Version"),
author = (string)x.Element("VersionInfo").Attribute("Author"),
date = (DateTime)x.Element("VersionInfo").Attribute("Date"),
remarks = (string)x.Element("VersionInfo").Attribute("Remarks"),
eventInputs = x.Descendants("EventInputs").FirstOrDefault().Elements("Event").Select(y => (string)y.Attribute("Name")).ToArray(),
eventOutputs = x.Descendants("EventOutputs").FirstOrDefault().Elements("Event").Select(y => (string)y.Attribute("Name")).ToArray(),
}).ToList();
foreach (FBTType fbTType in fBTTypes)
{
fbTType.print();
}
Console.ReadLine();
}
}
public class FBTType
{
public string guid { get; set; }
public string typeName { get; set; }
public string comment { get; set; }
public string ns { get; set; }
public string name { get; set; }
public string value { get; set; }
public string identification { get; set; }
public string organization { get; set; }
public string version { get; set; }
public string author { get; set; }
public DateTime date { get; set; }
public string remarks { get; set; }
public string[] eventInputs { get; set; }
public string[] eventOutputs { get; set; }
public void print()
{
Console.WriteLine("GUID : '{0}'",guid);
Console.WriteLine("Type Name : '{0}'",typeName);
Console.WriteLine("Comment : '{0}'",comment);
Console.WriteLine("Namespace : '{0}'",ns);
Console.WriteLine("Name : '{0}'",name);
Console.WriteLine("Value : '{0}'",value);
Console.WriteLine("Identification : '{0}'",identification);
Console.WriteLine("Organization : '{0}'",organization);
Console.WriteLine("Version : '{0}'",version);
Console.WriteLine("Author: '{0}'",author);
Console.WriteLine("Date : '{0}'",date.ToString());
Console.WriteLine("Remarks : '{0}'",remarks);
Console.WriteLine("Event Inputs : '{0}'",string.Join(",", eventInputs));
Console.WriteLine("Envent Outputs : '{0}'", string.Join(",", eventOutputs));
}
}
}
PHP XML DOM parseing mixed content
You can use XPath to select the text()
nodes and @b
to select the attribute and the union operator |
will bring all in the right order:
$xml = <<<EOD
<foo>
<bar>text <element a="1" b="2" c="3" /> and some more text</bar>
<bar>Just text</bar>
</foo>
EOD;
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$nodeList = $xpath->query('//foo//text() | //foo//element/@b', $doc);
$result = '';
for ($i = 0; $i < $nodeList->length; $i++) {
$result .= $nodeList[$i]->textContent;
}
echo $result;
Result is
text 2 and some more text
Just text
Related Topics
How to Clear Apc Cache Entries
Fastest Way to Convert String to Integer in PHP
Page Redirect After Certain Time PHP
PHP - How to Best Determine If the Current Invocation Is from Cli or Web Server
PHP Password_Hash(), Password_Verify()
Why Is Register_Globals So Bad
Set Cookie Wih Js, Read With PHP Problem
How to Embed Youtube Videos in PHP
PHP How to Get Local Ip of System
How to Make Dot Match Newline Characters Using Regular Expressions
Calculate Age Based on Date of Birth
PHP: Check If an Array Contains All Array Values from Another Array
Fatal Error: Call to a Member Function Prepare() on Null
How to Access MySQL Result Set Data With a Foreach Loop
PHP Regular Expression to Match Keyword Outside HTML Tag ≪A≫