0

私はsimplexmlを使用して、ワードプレスサイトからのデータでxmlファイルを更新しています。誰かがページにアクセスするたびに、ページIDとビューカウンターを次のようなネストされた構造でファイルに追加したいと思います…</ p>

<posts>
    <post>
        <postid>3231</postid>
        <postviews>35</postviews>
    </post>
    <post>
        <postid>7634</postid>
        <postviews>1</postviews>
    </post>
</posts>

私が抱えている問題は、挿入が間違った場所で行われていることです-そして私は次のようになっています... </ p>

<posts>
    <post>
        <postid>3231</postid>
        <postviews>35</postviews>
    <postid>22640</postid><postviews>1</postviews><postid>22538</postid><postviews>1</postviews></post>
</posts>

ご覧のとおり、ノード<postid>とノードは新しい親<postviews>にラップされていません。<post>誰かが私を助けることができます、それは私を狂わせています!

これは、投稿IDが存在するかどうかを確認し、存在しない場合は追加しないためのこれまでの私のコードです…</ p>

//Get the wordpress postID
$postID = get_the_ID();

$postData = get_post($postID);

//echo $postID.'<br />'.$postData->post_title.'<br />'.$postData->post_date_gmt.'<br />';

// load the document
$xml = simplexml_load_file('/Applications/MAMP/htdocs/giraffetest/test.xml');

// Check to see if the post id is already in the xml file - has it already been set?
$nodeExists = $xml->xpath("//*[contains(text(), ".$postID.")]");

//Count the results
$countNodeExists = count($nodeExists);

if($countNodeExists > 0) {

    echo 'ID already here';

} else {
    echo 'ID not here';

    $postNode = $xml->post[0];
    $postNode->addChild('postid', $postID);
    $postNode->addChild('postviews', 1);
}

// save the updated document
$xml->asXML('/Applications/MAMP/htdocs/giraffetest/test.xml');

どうもありがとう、ジェームズ

4

1 に答える 1

0

xmlドキュメント内に新しい要素が必要な場合は、コードのどこかに<post>あるはずです。次のようにパーツをaddChild('post')変更します。else

/* snip */
} else {
    $postNode = $xml->addChild('post'); // adding a new <post> to the top level node
    $postNode->addChild('postid', $postID); // adding a <postid> inside the new <post>
    $postNode->addChild('postviews', 1); // adding a postviews inside the new <post>
}
于 2012-11-22T09:12:42.657 に答える