Регистрация Войти
Войти через VK Войти через FB Войти через Google Войти через Яндекс
Войти через VK Войти через FB Войти через Google Войти через Яндекс
Поиск по сайту
Класс SimpleXMLElement
(PHP 5 >= 5.0.1)
Введение
Представляет собой элемент в XML-документе.
Обзор классов
SimpleXMLElement implements Traversable {
/* Методы */
final public __construct ( string $data [, int $options = 0 [, bool $data_is_url = false [, string $ns = "" [, bool $is_prefix = false ]]]] )
public void addAttribute ( string $name [, string $value [, string $namespace ]] )
public SimpleXMLElement addChild ( string $name [, string $value [, string $namespace ]] )
public mixed asXML ([ string $filename ] )
public SimpleXMLElement attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )
public SimpleXMLElement children ([ string $ns [, bool $is_prefix = false ]] )
public int count ( void )
public array getDocNamespaces ([ bool $recursive = false [, bool $from_root = true ]] )
public string getName ( void )
public array getNamespaces ([ bool $recursive = false ] )
public bool registerXPathNamespace ( string $prefix , string $ns )
public string __toString ( void )
public array xpath ( string $path )
}
Содержание
- SimpleXMLElement::addAttribute — Добавляет атрибут к SimpleXML-элементу
- SimpleXMLElement::addChild — Добавляет дочерний элемент к узлу XML
- SimpleXMLElement::asXML — Возвращает сформированный XML документ в виде строки используя SimpleXML элемент
- SimpleXMLElement::attributes — Возвращает атрибуты элемента
- SimpleXMLElement::children — Поиск дочерних элементов данного узла
- SimpleXMLElement::__construct — Создание нового SimpleXMLElement объекта
- SimpleXMLElement::count — Считает количество дочерних элементов у текущего элемента
- SimpleXMLElement::getDocNamespaces — Возвращает объявленное пространство имен в документе
- SimpleXMLElement::getName — Получение имени XML элемента
- SimpleXMLElement::getNamespaces — Получение пространств имен, используемых в документе
- SimpleXMLElement::registerXPathNamespace — Создает префикс/пространство имен контекста для следующего XPath запроса
- SimpleXMLElement::saveXML — Псевдоним SimpleXMLElement::asXML
- SimpleXMLElement::__toString — Returns the string content
- SimpleXMLElement::xpath — Запускает XPath запрос к XML данным
foreach($doc->seg as $key => $seg)
{
if((string)$seg['id'] === 'whatever')
{
unset($seg); // only clears local copy
unset($seg[$key]); // wrong index "seg"
}
}
12
Anonymous ¶3 years ago
$xml = simplexml_load_string($input);
$callback = $xml->{"callback-url"};
4
cherubangel at gmail dot com ¶4 years ago
foreach($xmlelement -> attributes('xlink', true) as $attribute => $attribvalue){
$attribvalue[0] = 'value'; // Throws an error
$attribvalue = 'value'; // Does not change your XML
$xmlelement -> addAttribute($attribute, 'value', 'http://www.w3.org/1999/xlink'); // Adds an attribute, does not change existing one.
$xmlelement[$attribute] = 'value'; // Adds an attribute, does not change existing one.
}
3
saganmarketing.com ¶3 years ago
function XML2JSON($xml) {
function normalizeSimpleXML($obj, &$result) {
$data = $obj;
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
foreach ($data as $key => $value) {
$res = null;
normalizeSimpleXML($value, $res);
if (($key == '@attributes') && ($key)) {
$result = $res;
} else {
$result[$key] = $res;
}
}
} else {
$result = $data;
}
}
normalizeSimpleXML(simplexml_load_string($xml), $result);
return json_encode($result);
}
5
brett at brettbrewer dot com ¶5 years ago
$sxml= new SimpleXmlElement($xmlstr);
if ((string) $sxml->property== "somevalue") {
echo (string) $sxml->property;
}
1
ivandosreisandrade at gmail dot com ¶5 years ago
$xmlstr = "<?xml version='1.0'
3
francs at seznam dot cz ¶4 years ago
$obj = new SimpleXMLElement('<root>
<a>1.9</a>
<b>1.9</b>
</root>');
var_dump($obj->a + $obj->b);
var_dump((float)$obj->a + (float)$obj->b);
var_dump((string)$obj->a + (string)$obj->b);
1
php at keith tyler dot com ¶5 years ago
$xml="<foo>bar</foo>";
$sxe=new SimpleXMLElement($xml);
print $sxe->foo;
1
triplepoint at gmail dot com ¶5 years ago
class SimpleXMLElement_Plus extends SimpleXMLElement {
public function addProcessingInstruction( $name, $value )
{
// Create a DomElement from this simpleXML object
$dom_sxe = dom_import_simplexml($this);
// Create a handle to the owner doc of this xml
$dom_parent = $dom_sxe->ownerDocument;
// Find the topmost element of the domDocument
$xpath = new DOMXPath($dom_parent);
$first_element = $xpath->evaluate('/*[1]')->item(0);
// Add the processing instruction before the topmost element
$pi = $dom_parent->createProcessingInstruction($name, $value);
$dom_parent->insertBefore($pi, $first_element);
}
}
1
Yukull ¶2 years ago
/**
@param:
$xml: SimpleXMLElement
$force: set to true to always create 'text', 'attribute', and 'children' even if empty
@return
object with attributs:
(string) name: XML tag name
(string) text: text content of the attribut name
(array) attributes: array witch keys are attribute key and values are attribute value
(array) children: array of objects made with xml2obj() on each child
**/
function xml2obj($xml,$force = false){
$obj = new StdClass();
$obj->name = $xml->getName();
$text = trim((string)$xml);
$attributes = array();
$children = array();
foreach($xml->attributes() as $k => $v){
$attributes[$k] = (string)$v;
}
foreach($xml->children() as $k => $v){
$children[] = xml2obj($v,$force);
}
if($force or $text !== '')
$obj->text = $text;
if($force or count($attributes) > 0)
$obj->attributes = $attributes;
if($force or count($children) > 0)
$obj->children = $children;
return $obj;
}
2
ms dot n at 163 dot com ¶4 years ago
class CeiXML extends SimpleXMLElement{
public function asHTML(){
$ele=dom_import_simplexml($this);
$dom = new DOMDocument('1.0', 'utf-8');
$element=$dom->importNode($ele,true);
$dom->appendChild($element);
return $dom->saveHTML();
}
}
-1
Pavel Musil pavel dot musil at gmail dot com ¶4 years ago
// root: parent element - SimpleXMLElement instance
// append: XML object from simplexml_load_string
function xml_join($root, $append) {
if ($append) {
if (strlen(trim((string) $append))==0) {
$xml = $root->addChild($append->getName());
foreach($append->children() as $child) {
xml_join($xml, $child);
}
} else {
$xml = $root->addChild($append->getName(), (string) $append);
}
foreach($append->attributes() as $n => $v) {
$xml->addAttribute($n, $v);
}
}
}
$xml_append = simplexml_load_string('<data><items><item id="1">value</item></items></data>');
$xml_root = new SimpleXMLElement('<result></result>');
$cxml = $xml_root->addChild('clone');
xml_join($cxml, $xml_append->items->item[0]);
print $xml_root->asXML();
-1
kweij at lsg dot nl ¶4 years ago
function SimpleXMLElement_append($key, $value) {
// check class
if ((get_class($key) == 'SimpleXMLElement') && (get_class($value) == 'SimpleXMLElement')) {
// check if the value is string value / data
if (trim((string) $value) == '') {
// add element and attributes
$element = $key->addChild($value->getName());
foreach ($value->attributes() as $attKey => $attValue) {
$element->addAttribute($attKey, $attValue);
}
// add children
foreach ($value->children() as $child) {
SimpleXMLElement_append($element, $child);
}
} else {
// set the value of this item
$element = $key->addChild($value->getName(), trim((string) $value));
}
} else {
// throw an error
throw new Exception('Wrong type of input parameters, expected SimpleXMLElement');
}
}
-4
dans at dansheps dot com ¶3 years ago
function parseSimpleXML($xmldata)
{
$childNames = array();
$children = array();
if( $xmldata->count() !== 0 )
{
foreach( $xmldata->children() AS $child )
{
$name = $child->getName();
if( !isset($childNames[$name]) )
{
$childNames[$name] = 0;
}
$childNames[$name]++;
$children[$name][] = $this->parseSimpleXML($child);
}
}
$returndata = new XMLNode();
if( $xmldata->attributes()->count() > 0 )
{
$returndata->{'@attributes'} = new XMLAttribute();
foreach( $xmldata->attributes() AS $name => $attrib )
{
$returndata->{'@attributes'}->{$name} = (string)$attrib;
}
}
if( count($childNames) > 0 )
{
foreach( $childNames AS $name => $count )
{
if( $count === 1 )
{
$returndata->{$name} = $children[$name][0];
}
else
{
$returndata->{$name} = new XMLMultiNode();
$counter = 0;
foreach( $children[$name] AS $data )
{
$returndata->{$name}->{$counter} = $data;
$counter++;
}
}
}
}
else
{
if( (string)$xmldata !== '' )
{
$returndata->{'@innerXML'} = (string)$xmldata;
}
}
return $returndata;
}
Описание класса simplexmlelement, примеры использования класса simplexmlelement.
Смотрите также:
Описание на ru2.php.net
Описание на php.ru