Getting the text part of a node using php Simple XML

Given the php code:

$xml = <<<EOF
<articles>
<article>
This is a link
<link>Title</link>
with some text following it.
</article>
</articles>
EOF;

function traverse($xml) {
    $result = "";
    foreach($xml->children() as $x) {
        if ($x->count()) {
            $result .= traverse($x);
        }
        else {
            $result .= $x;
        }
    }
    return $result;
}

$parser = new SimpleXMLElement($xml);
traverse($parser);

I expected the traverse () function to return:

This is a link Title with some text following it.

However, it only returns:

Title

Is there a way to get the expected result using simpleXML (obviously, for the purpose of consuming data, and not just returning it, as in this simple example)?

Thank you N.

+5
source share
7 answers

, , SimpleXML, - DOM. , SimpleXML, , DOM SimpleXML :

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

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

, , <article/> ,

$articles = simplexml_load_string($xml);
foreach ($articles->article as $article)
{
    $articleText = dom_import_simplexml($article)->textContent;
}
+15
node->asXML();// It the simple solution i think !!
+4

, : Simplexml XML. DomDocument.

, XML. , DomDocument XML, SimpleXML , XML .

function attrs($list) {
    $result = "";
    foreach ($list as $attr) {
        $result .= " $attr->name='$attr->value'";
    }
    return $result;
}

function parseTree($xml) {
    $result = "";
    foreach ($xml->childNodes AS $item) {
        if ($item->nodeType == 1) {
            $result .= "<$item->nodeName" . attrs($item->attributes) . ">" . parseTree($item) . "</$item->nodeName>";
        }
        else {
            $result .= $item->nodeValue;
        }
    }
    return $result;
}

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xml);

print parseTree($xmlDoc->documentElement);

xml simpleXML, DOM, dom_import_simplexml(), . , simpleXml , . XPath.

simpleXML, .

$simpleXml = new SimpleXMLElement($xml);
$xmlDom = dom_import_simplexml($simpleXml);

print parseTree($xmlDom);

!

+3

node DOM simplexml, :

foreach($xml->children() as $x) {
   $result .= "$x"

:

This is a link

with some text following it.
TitleTitle

.. node , , node. node - else {}, .

, , , , node node, xml ( ). , , strip_tags() .

+1

, CASTING TO STRING ( $sString = () oSimpleXMLNode- > TagName) .

+1

@tandu, , XML, :

$xml = <<<EOF
<articles>
    <article>
        This is a link
    </article>
    <link>Title</link>
    <article>
       with some text following it.
    </article>
</articles>
0

:

$parser = new SimpleXMLElement($xml);
echo strip_tags($parser->asXML());

:

$parser = simplexml_load_string($xml);
echo dom_import_simplexml($parser)->textContent;
0

All Articles