Basic Simplexml Working Example

Basic simpleXML working example?

SimpleXML 101

  1. First of all, always name your PHP variables after the node they represent.

    // the root node is <programme/>
    $programme = simplexml_load_file("local.xml");
  2. Access to children (nodes) as if they were object properties.

    echo $programme->title;
  3. If there are multiple children using the same name, you can specify their 0-based position

    // first <title/> child
    echo $programme->title[0];

    // create or change the value of the second <title/> child
    $programme->title[1] = 'Second title';
  4. Access to attributes as if they were array keys

    // <mynode attr="attribute value" />
    echo $mynode['attr'];
  5. XPath always returns an array.


Back to your case, the best way to access that <title /> node would be

$programme = simplexml_load_file("local.xml");
echo "Title: " . $programme->title;

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>

Have fun.

Working with very complex XML files in PHP (SimpleXML)

The SimpleXML ->xpath() function returns an array of SimpleXML objects, each representing an element or attribute which matches your XPath expression.

So firstly, you need to loop over the results (or take the first one with [0]); and secondly, you need to do something with the SimpleXML object found. If it's an attribute, (string)$sx_attrib will give you its value; otherwise, you'll need to do further manipulation.

Finally, don't use var_dump, print_r, or var_export on SimpleXML objects, as they're not "real" PHP objects but wrappers around non-PHP data. Use simplexml_dump instead.

Get an attribute value using SimpleXML for PHP

You can use the attributes() function on the node to get it's attributes:

$xml_str = '<xml>
<node>
<someTag cp="c2">content</someTag>
</node>
</xml>';
$res = simplexml_load_string($xml_str);

$items = $res->xpath("//someTag");
var_dump((string) $items[0]->attributes()->cp);

The returned element is an SimpleXMLElement, so in order to use it I converted it to string (using the (string) cast).

Getting the text portion of a node using php Simple XML

There might be ways to achieve what you want using only SimpleXML, but in this case, the simplest way to do it is to use DOM. The good news is if you're already using SimpleXML, you don't have to change anything as DOM and SimpleXML are basically interchangeable:

// either
$articles = simplexml_load_string($xml);
echo dom_import_simplexml($articles)->textContent;

// or
$dom = new DOMDocument;
$dom->loadXML($xml);
echo $dom->documentElement->textContent;

Assuming your task is to iterate over each <article/> and get its content, your code will look like

$articles = simplexml_load_string($xml);
foreach ($articles->article as $article)
{
$articleText = dom_import_simplexml($article)->textContent;
}

How to echo an PHP SimpleXMLElement

change this line:

$movies = new SimpleXMLElement($xml);

to this:

$movies = new SimpleXMLElement($xml->asXML());

Accessing @attribute from SimpleXML

You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.

More info at php.net
http://php.net/simplexmlelement.attributes

Example code from that page:

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}

PHP: Using simplexml to loop through all levels of an XML file

So basically what you need to do is a function that takes each <asset/> child of current node, builds the HTML then checks if the current node has <asset/> children of its own and keeps recursing deeper down the tree.

Here's how you can do it:

function printAssetMap()
{
return printAssets(simplexml_load_file(X_ASSETS));
}

function printAssets(SimpleXMLElement $parent)
{
$html = "<ul>\n";
foreach ($parent->asset as $asset)
{
$html .= printAsset($asset);
}
$html .= "</ul>\n";

return $html;
}

function printAsset(SimpleXMLElement $asset)
{
$html = '<li id="asset'.$asset->asset_assetid.'"><ins> </ins><a href="#">'.$asset->asset_name.' ['.$asset->asset_assetid.']</a>';

if (isset($asset->asset))
{
// has <asset/> children
$html .= printAssets($asset);
}

$html .= "</li>\n";

return $html;
}

By the way, I would expect a function named "printX" to actually print or echo something, rather than return it. Perhaps you should name those functions "buildX" ?

SimpleXML get node value

$xml = new SimpleXMLElement($xml);
$this->xmlcode = (string) $xml->parent[0]->child1;

SimpleXML: Working with XML containing namespaces

You could work with XPath and registerXPathNamespace():

$xml->registerXPathNamespace("georss", "http://www.georss.org/georss");
$xml->registerXPathNamespace("gml", "http://www.opengis.net/gml");
$pos = $xml->xpath("/georss:where/gml:Point/gml:pos");

From the docs, emphasis mine:

registerXPathNamespace […] Creates a prefix/ns context for the next XPath query.

More ways to handle namespaces in SimpleXML can be found here, for example:

Stuart Herbert On PHP - Using SimpleXML To Parse RSS Feeds



Related Topics



Leave a reply



Submit